Flutter - Package Tutorial not working when passing StreamBuilder in body - flutter

I will be very direct, I use package Tutorial link: https://pub.dev/packages/tutorial
But I'm having trouble making it work with StreamBuilder.
Example that works:
import 'package:flutter/material.dart';
import 'package:tutorial/tutorial.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<TutorialItem> itens = [];
final _keyDrawer = GlobalKey();
final _keyAccount = GlobalKey();
final _keyContainer = GlobalKey();
#override
void initState() {
itens.addAll({
TutorialItem(
globalKey: _keyDrawer,
touchScreen: true,
top: 200,
left: 50,
children: [
const Text(
"Ali é nosso menu , você consegue ver varias coisas nele",
style: TextStyle(color: Colors.white, fontSize: 20),
),
const SizedBox(
height: 100,
)
],
widgetNext: const Text(
"Toque para continuar",
style: TextStyle(
color: Colors.purple,
fontWeight: FontWeight.bold,
),
),
shapeFocus: ShapeFocus.oval),
TutorialItem(
globalKey: _keyAccount,
touchScreen: true,
top: 200,
left: 50,
children: [
const Text(
"Qualquer duvida que aparecer , entre no nosso chat , estamos prontos para ajudar",
style: TextStyle(color: Colors.white, fontSize: 20),
),
const SizedBox(
height: 100,
)
],
widgetNext: const Text(
"Toque para continuar",
style: TextStyle(
color: Colors.purple,
fontWeight: FontWeight.bold,
),
),
shapeFocus: ShapeFocus.oval,
),
TutorialItem(
globalKey: _keyContainer,
touchScreen: true,
top: 200,
left: 50,
children: [
const Text(
"Aqui veremos todo container",
style: TextStyle(color: Colors.white, fontSize: 20),
),
const SizedBox(
height: 100,
)
],
widgetNext: const Text(
"Toque para continuar",
style: TextStyle(
color: Colors.purple,
fontWeight: FontWeight.bold,
),
),
shapeFocus: ShapeFocus.square,
),
});
///FUNÇÃO QUE EXIBE O TUTORIAL.
Future.delayed(const Duration(microseconds: 200)).then((value) {
Tutorial.showTutorial(context, itens);
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Teste tutorial"),
leading: Builder(builder: (context) {
return IconButton(
key: _keyDrawer,
onPressed: () {
Scaffold.of(context).openDrawer();
},
icon: const Icon(
Icons.menu,
color: Colors.white,
),
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
);
}),
actions: [
IconButton(
key: _keyAccount,
onPressed: () {},
icon: const Icon(Icons.account_circle_outlined))
],
),
body: Stack(
children: <Widget>[
createListView(
context,
)
],
),
drawer: const Drawer(),
);
}
final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];
Widget createListView(
BuildContext context,
) {
return ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return Container(
key: index == 0 ? _keyContainer : null,
height: 50,
color: Colors.blue[colorCodes[index]],
child: Center(child: Text('Entry ${entries[index]}')),
);
});
}
}
expected result and working in the first example
What is not working is when my body is passed a StreamBuilder that returns a CreateListView:
body: Stack(
children: <Widget>[
_buildBodyBack(),
StreamBuilder<bool>(
stream: _syncservice.outLoading,
initialData: false,
builder: (context, snapshot) {
if (snapshot.data == true)
return loading(title: "Sync Data...");
return StreamBuilder<bool>(
stream: _propertyService.outLoading,
initialData: false,
builder: (context, snapshot) {
if (snapshot.data == true)
return loading(title: "Loading Property...");
return StreamBuilder<List<Property>>(
stream: _propertyService.outProperty,
initialData: null,
builder: (context, snapshot) {
if (snapshot.data == null) return Container();
return createListView(
context,
snapshot,
);
});
},
);
},
),
],
),
Using the stream builder and passing my createListView widget the key like this:
key: _keyExampleName (Key name example)
Even passing the key correctly it doesn't work as the first example

Related

How to manually add items to listview in Flutter

I have a list of cart items which I am displaying using the code below. Right after this list, I would like to display the total amount. This is how the final result should look like:
Chicken Burger 1X $20.5
Chicken Wrap 1X $9.99
Total $30.49
Container(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 4),
height: min(widget.order.products.length * 20.0 + 10, 100),
child: ListView(
children: widget.order.products
.map(
(prod) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(child:Text(
prod.title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
)),
Text(
'${prod.quantity}x \$. ${prod.price}',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
)
],
),
)
.toList(),
How can I append total to this list?
Here is my suggestion.
I used spread operator to ListView's children for adding Widget related to 'total'.
Additionally I added one item at Container's height because of Total item in ListView.
Below is summary code that I did.
ListView(
children: <Widget> [
...list.map(...).toList(),
TotalWidget(),
]
)
This is full code based your code.
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: () {
showModalBottomSheet(
context: context,
backgroundColor: Colors.blueGrey,
isScrollControlled: false,
builder: (context) => Wrap(
children: [
ListView.separated(
shrinkWrap: true,
itemCount: 3,
itemBuilder: (BuildContext context, int index) => ListTile(
title: Text(
'lists[index].listName',
style: TextStyle(
color: Colors.white,
),
),
),
separatorBuilder: (BuildContext context, int index) =>
Divider(),
),
],
),
);
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Widget _buildBody() {
List<Product> listProduct = [
Product('Chicken Burger', 1, 20.5),
Product('Chicken Wrap', 1, 9.99),
];
double totalAmount = 0;
for (var item in listProduct) {
totalAmount += (item.price * item.quantity);
}
return Container(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 4),
height: min((listProduct.length + 1) * 20.0 + 10, 100),
child: ListView(
children: [
...listProduct
.map(
(prod) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Text(
prod.title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
)),
Text(
'${prod.quantity}x \$. ${prod.price}',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
)
],
),
)
.toList(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Text(
'Total',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
)),
Text(
'$totalAmount',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
)
])
],
),
);
}
}
class Product {
String title;
int quantity;
double price;
Product(this.title, this.quantity, this.price);
}
Edit 1, after op updated more info in comments:
Column(children: [ Text(widget.order.totalPrice.toString()),
Flexible(child:
ListView(
children:
widget.order.products
.map((prod) => Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(child:Text(
prod.title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
)),
Text(
'${prod.quantity}x \$. ${prod.price}',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
)
],
),
)
.toList())]),
Since total isn't being stored as a single variable your list\cart object. You need to create a double totalPrice = 0.0;
then use a forLoop to add the values
for (var prod in widget.order.products) {
totalPrice += (prod.price * prod.quantity);}
Display this totalPrice wherever you want, you can't have it in the listView though.
If you want add items to ListView, first you have to add those items to your List (for example order.products or new one) and then use state management approach to re render ListView. if your logic is simple you can use stateful widget.
example code:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: MyList(),
),
);
}
}
class MyList extends StatefulWidget {
#override
_MyListState createState() => _MyListState();
}
class _MyListState extends State<MyList> {
List<String> orders = ["order1", "order2", "order3"];
#override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: ListView(
children: orders
.map(
(String e) => Card(
child: ListTile(
title: Text(e),
),
),
)
.toList(),
),
),
TextButton(
onPressed: () {
List<String> extraFields = ["field1", "field2"];
setState(
() {
orders.addAll(extraFields);
},
);
},
child: Text("Add extra fields"),
),
],
);
}
}
For that, you'd have to learn state management. To make things simple we'll use the built-in StreamBuilder to provide the data. Its best practice to separate your ui from your business logic so I'll do it here.
In order to use a StreamBuilder, you'd have to provide it a Stream<T> where T is your variable's type. In your case, its a List<String>. Lets write it in another file that holds all your buisness logic.
product_bloc.dart:
class ProductBloc {
final List<String> _productList = ["Item One", "Item Two"];
StreamController<List<String>> _products = StreamController<List<String>>();
Stream<List<String>> get products => _products.stream;
ProductBloc() {
_products.add(_productList);
}
void addProductAfterDelay() async {
_productList.add("Item Three");
await Future.delayed(const Duration(seconds: 3));
_products.add(_productList);
}
}
product_screen.dart:
StreamBuilder<List<String>>(
initialData: [],
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Text(snapshot.data[index]);
});
},
);

Flutter Searchdelegate, i want to add background color and appbar color when i click the search

i can change my background color and app bar in home just fine, but when i click the search icon which uses search delegate it all back to white, how do i change the color? just to make it clear, so before the user clicked the search icon the background and app bar was black but when they clicked it it turned to white, how do i change it?
here is the search code :
import 'package:flutter/material.dart';
import 'package:movie_app_3/model/movie_response.dart';
import 'package:movie_app_3/screens/movie_detail_screen/movie_detail_screen.dart';
import '../model/movie.dart';
import '../repository/repository.dart';
class DataSearch extends SearchDelegate {
// void initState() {
// searchBloc..getSearch(query);
// }
final movieRepo = MovieRepository();
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () => query = '',
)
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
onPressed: () => close(context, null),
);
}
#override
Widget buildResults(BuildContext context) {
return Container();
}
#override
Widget buildSuggestions(BuildContext context) {
if (query.isEmpty) return Container();
return FutureBuilder<MovieResponse>(
future: movieRepo.getSearch(query),
builder: (BuildContext context, AsyncSnapshot<MovieResponse> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.error != null && snapshot.data.error.length > 0) {
return _buildErrorWidget(snapshot.data.error);
}
return _buildHomeWidget(snapshot.data);
} else if (snapshot.hasError) {
return _buildErrorWidget(snapshot.error);
} else {
return _buildLoadingWidget();
}
},
);
}
Widget _buildHomeWidget(MovieResponse data) {
List<Movie> movies = data.movies;
return ListView.builder(
itemCount: movies.length,
itemBuilder: (context, index) {
return ListTile(
leading: FadeInImage(
image: movies[index].poster == null
? AssetImage('assets/images/no-image.jpg')
: NetworkImage("https://image.tmdb.org/t/p/w200/" +
movies[index].poster),
placeholder: AssetImage('assets/images/no-image.jpg'),
width: 50.0,
fit: BoxFit.contain),
title: Text(
movies[index].title,
style: TextStyle(fontFamily: 'Poppins'),
),
subtitle: Text(
movies[index].overview,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontFamily: 'Raleway'),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MovieDetailScreen(movie: movies[index]),
),
);
},
);
},
);
}
Widget _buildLoadingWidget() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 25.0,
width: 25.0,
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation<Color>(Colors.black),
strokeWidth: 4.0,
),
)
],
));
}
Widget _buildErrorWidget(String error) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Error occured: $error"),
],
));
}
// #override
// Widget buildSuggestions(BuildContext context) {
// final suggestedList = (query.isEmpty) ?
// recentMovies :
// movies.where((movie) => movie.toLowerCase().contains(query.toLowerCase())).toList();
// return ListView.builder(
// itemCount: suggestedList.length,
// itemBuilder: (context, i) {
// return ListTile(
// leading: Icon(Icons.movie),
// title: Text(suggestedList[i]),
// onTap: () {},
// );
// },
// );
// }
}
here is the home code :
import 'package:flutter/material.dart';
import 'package:movie_app_3/widget/drawer.dart';
import 'package:movie_app_3/screens/home_screen/widget/home_screen1.dart';
import 'package:movie_app_3/screens/home_screen/widget/home_screen2.dart';
import 'package:movie_app_3/widget/search.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: 2);
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black,
Color(0xff112339),
Colors.black,
],
),
),
child: DefaultTabController(
length: 2,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
elevation: 0,
title: Text(
'Moviez',
style: TextStyle(
fontSize: 24,
color: Colors.white,
fontFamily: 'Poppins',
),
),
backgroundColor: Colors.transparent,
centerTitle: true,
actions: [
Padding(
padding: EdgeInsets.only(right: 20),
child: IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch());
},
),
),
],
bottom: TabBar(
controller: _tabController,
indicatorColor: Colors.white,
indicatorSize: TabBarIndicatorSize.tab,
indicatorWeight: 2.0,
tabs: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Discover',
style: TextStyle(fontSize: 16, fontFamily: 'Raleway'),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Genres',
style: TextStyle(fontSize: 16, fontFamily: 'Raleway'),
),
),
],
),
),
drawer: MyDrawer(),
body: TabBarView(
controller: _tabController,
children: <Widget>[
FirstTab(),
SecondTab(),
],
),
),
),
);
}
}
For customizing the Search Delegate, you have to override a method called appBarTheme and then set your custom theme on that.
** NOTE: When you override appBarTheme of SearchDelegate you have to customize evrything related to SearchBar yourself. Just like the code below. **
Do this to change the AppBar Color:
#override
ThemeData appBarTheme(BuildContext context) {
return ThemeData(
appBarTheme: const AppBarTheme(
color: MyColors.mainColor, // affects AppBar's background color
hintColor: Colors.grey, // affects the initial 'Search' text
textTheme: const TextTheme(
headline6: TextStyle( // headline 6 affects the query text
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.bold)),
),
);
}
And for changing the background color of suggestions:
#override
Widget buildSuggestions(BuildContext context) {
return Container(
color: Colors.black,
...
);
}
Similarly do this for results:
#override
Widget buildResults(BuildContext context) {
return Container(
color: Colors.black,
...
);
}
Hope this helps.
Add this to your "DataSearch" class
class _SearchDelegate extends SearchDelegate {
#override
ThemeData appBarTheme(BuildContext context) {
return Theme.of(context).copyWith(
scaffoldBackgroundColor: Colors.green,
);
}
If you already set your MaterialApp theme you can simply use Theme.of(context).copywith to remain body theme. Then you can override appBarTheme to change desired color/styles.
#override
ThemeData appBarTheme(BuildContext context) {
return Theme.of(context).copyWith(
//scaffoldBackgroundColor: , to change scaffold color
appBarTheme: const AppBarTheme( //to change appbar
color: Colors.black,
//titleTextStyle: , to change title text
//toolbarTextStyle: , to change toolbar text style
),
);

Flutter StatefulWidget parameter unable to pass

I know there was a really similar case and got solved, I modified my code to 99% liked to that but somehow my list is undefined.
The list that is undefined is at the line where ' ...(list as List).map((answer) { '.
import 'package:flutter/material.dart';
import 'package:kzstats/common/AppBar.dart';
import 'package:kzstats/common/Drawer.dart';
import '../toggleButton.dart';
class Settings extends StatelessWidget {
final String currentPage = 'Settings';
static const _modes = [
{
'mode': ['KZTimer', 'SimpleKZ', 'Vanilla']
},
{
'tickrate': [128, 102, 64]
},
];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: HomepageAppBar(currentPage),
drawer: HomepageDrawer(),
body: Padding(
padding: EdgeInsets.all(8),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildHeader(
title: 'Mode',
child: ToggleButton(_modes[0]['mode']),
),
SizedBox(height: 32),
buildHeader(
title: 'Tick rate',
child: ToggleButton(_modes[1]['tickrate']),
),
],
),
),
),
),
);
}
}
Widget buildHeader({#required String title, #required Widget child}) => Column(
children: [
Text(
title,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
child,
],
);
class ToggleButton extends StatefulWidget {
final List<String> list;
ToggleButton(this.list);
#override
State createState() => new _ToggleButtonState();
}
class _ToggleButtonState extends State<ToggleButton> {
List<bool> _selections = [true, false, false];
#override
Widget build(BuildContext context) {
return new Container(
color: Colors.blue.shade200,
child: ToggleButtons(
isSelected: _selections,
fillColor: Colors.lightBlue,
color: Colors.black,
selectedColor: Colors.white,
renderBorder: false,
children: <Widget>[
...(list as List<String>).map((answer) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 12),
child: Text(
answer,
style: TextStyle(fontSize: 18),
),
);
}).toList(),
],
onPressed: (int index) {
setState(() {
for (int i = 0; i < _selections.length; i++) {
if (index == i) {
_selections[i] = true;
} else {
_selections[i] = false;
}
}
});
},
),
);
}
}
In case someone needs the full code, it's available at https://github.com/davidp918/KZStats
I'm new to Flutter and stackoverflow so if anything please just comment, thanks!
We can access a variable of StatefulWidget from the state class using "widget" (for example: widget.list)
Please refer below code sample for the reference.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Settings());
}
}
class Settings extends StatelessWidget {
final String currentPage = 'Settings';
static const modes = [
{
'mode': ['KZTimer', 'SimpleKZ', 'Vanilla']
},
{
'tickrate': [128, 102, 64]
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
child: Padding(
padding: EdgeInsets.all(8),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildHeader(
title: 'Mode',
child: ToggleButton(modes[0]['mode']),
),
SizedBox(height: 32),
buildHeader(
title: 'Tick rate',
child: ToggleButton(modes[1]['tickrate']),
),
SizedBox(height: 32),
buildHeader(
title: 'Mode',
child: ToggleButton(modes[0]['mode']),
),
],
),
),
),
),
),
);
}
}
Widget buildHeader({#required String title, #required Widget child}) {
return Column(
children: [
Text(
title,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
SizedBox(height: 16),
child,
],
);
}
class ToggleButton extends StatefulWidget {
final List list;
ToggleButton(this.list);
#override
State createState() => new _ToggleButtonState();
}
class _ToggleButtonState extends State<ToggleButton> {
List<bool> _selections = [false, false, false];
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blue.shade200,
child: ToggleButtons(
isSelected: _selections,
fillColor: Colors.lightBlue,
color: Colors.black,
selectedColor: Colors.white,
renderBorder: false,
children: [
...(widget.list as List)?.map((answer) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 12),
child: Text(
answer.toString() ?? '',
style: TextStyle(fontSize: 18),
),
);
})?.toList(),
],
onPressed: (int index) {
setState(() {
for (int i = 0; i < _selections.length; i++) {
if (index == i) {
_selections[i] = true;
} else {
_selections[i] = false;
}
}
});
},
),
);
}
}

Flutter Onboarding - How to Swipe Two Images at The Same Time?

I want to swipe right background images with an end image located at the end of the bottom of the screen with floating action button and want to swipe right a list of images with background images like other onboarding screens works. Here I needed 3 screens, the Last screen will be a login page. I used the Transformer Page View package for this. Currently, I used an image in the floating action button, but it's not working. How I can do this?
import 'package:flutter/material.dart';
import 'package:onlycentertainment/pages/splashscreen.dart';
import 'package:transformer_page_view/transformer_page_view.dart';
class TestPage1 extends StatefulWidget {
final String title;
TestPage1({this.title});
#override
TestPage1State createState() {
return new TestPage1State();
}
}
class TestPage1State extends State<TestPage1> {
int _slideIndex = 0;
int _bottomIndex = 0;
final List<String> images = [
"assets/images/welcome01.jpg",
"assets/images/welcome02.jpg",
"assets/images/welcome01.jpg",
];
final List<String> text0 = [
"Welcome in your app",
"Enjoy teaching...",
"Showcase your skills",
"Friendship is great"
];
final List<String> text1 = [
"App for food lovers, satisfy your taste",
"Find best meals in your area, simply",
"Have fun while eating your relatives and more",
"Meet new friends from all over the world"
];
final IndexController controller = IndexController();
#override
Widget build(BuildContext context) {
TransformerPageView transformerPageView = TransformerPageView(
pageSnapping: true,
onPageChanged: (index) {
setState(() {
this._slideIndex = index;
this._bottomIndex = index;
});
},
loop: false,
controller: controller,
transformer: new PageTransformerBuilder(
builder: (Widget child, TransformInfo info) {
return SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: new Material(
child: new Container(
alignment: Alignment.center,
color: Colors.white,
child: Column(
children: <Widget>[
new ParallaxContainer(
child: new Image.asset(
images[info.index],
fit: BoxFit.cover,
),
position: info.position,
translationFactor: 400.0,
),
SizedBox(
height: 45.0,
),
new ParallaxContainer(
child: new Text(
text1[info.index],
textAlign: TextAlign.center,
style: new TextStyle(
color: Colors.white,
fontSize: 28.0,
fontFamily: 'Quicksand',
fontWeight: FontWeight.bold),
),
position: info.position,
translationFactor: 300.0,
),
],
),
),
),
);
}),
itemCount: 3);
return Scaffold(
backgroundColor: Color(0xff243951),
body: transformerPageView,
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: 70,
width: MediaQuery.of(context).size.width,
child: IconButton(icon: Image.asset('assets/images/asset1.png'), onPressed: (){
Navigator.of(context).push(MaterialPageRoute(builder: (context)=>SplashScreen()));
}),
),
);
}
}
I am not sure I understand correctly but, the problem of your code is "SplashScreen()" part, it can't be empty, I made a working sample, check out and let me know if I misunderstand the thing you wanted to do.
import 'package:flutter/material.dart';
import 'package:splashscreen/splashscreen.dart';
import 'package:transformer_page_view/transformer_page_view.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new TestPage1(title: 'Flutter Demo Home Page'),
);
}
}
class TestPage1 extends StatefulWidget {
final String title;
TestPage1({this.title});
#override
TestPage1State createState() {
return new TestPage1State();
}
}
class TestPage1State extends State<TestPage1> {
int _slideIndex = 0;
int _bottomIndex = 0;
final List<String> images = [
"assets/images/welcome01.jpg",
"assets/images/welcome02.jpg",
"assets/images/welcome01.jpg",
];
final List<String> text0 = [
"Welcome in your app",
"Enjoy teaching...",
"Showcase your skills",
"Friendship is great"
];
final List<String> text1 = [
"App for food lovers, satisfy your taste",
"Find best meals in your area, simply",
"Have fun while eating your relatives and more",
"Meet new friends from all over the world"
];
final IndexController controller = IndexController();
#override
Widget build(BuildContext context) {
TransformerPageView transformerPageView = TransformerPageView(
pageSnapping: true,
onPageChanged: (index) {
setState(() {
this._slideIndex = index;
this._bottomIndex = index;
});
},
loop: false,
controller: controller,
transformer: new PageTransformerBuilder(
builder: (Widget child, TransformInfo info) {
return SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: new Material(
child: new Container(
alignment: Alignment.center,
color: Colors.white,
child: Column(
children: <Widget>[
new ParallaxContainer(
child: new Image.asset(
images[info.index],
fit: BoxFit.cover,
),
position: info.position,
translationFactor: 400.0,
),
SizedBox(
height: 45.0,
),
new ParallaxContainer(
child: new Text(
text1[info.index],
textAlign: TextAlign.center,
style: new TextStyle(
color: Colors.white,
fontSize: 28.0,
fontFamily: 'Quicksand',
fontWeight: FontWeight.bold),
),
position: info.position,
translationFactor: 300.0,
),
],
),
),
),
);
}),
itemCount: 3);
return Scaffold(
backgroundColor: Color(0xff243951),
body: transformerPageView,
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: 70,
width: MediaQuery.of(context).size.width,
child: IconButton(icon: Image.asset(images[_bottomIndex]), onPressed: (){
Navigator.of(context).push(MaterialPageRoute(builder: (context)=>SplashScreen(
seconds: 4,
navigateAfterSeconds: new AfterSplash(),
title: new Text('Welcome In SplashScreen',
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0
),
)
)
)
);
}
),
),
);
}
}
class AfterSplash extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Welcome In SplashScreen Package"),
automaticallyImplyLeading: false,
),
body: new Center(
child: new Text("Succeeded!",
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30.0
),
),
),
);
}
}

How to validate the current date in (dd-mm) format with the passcode

I'm trying to build two screens where:
The first screen has a Pincode textfield when the user enters the current date in (dd-mm) format for eg: if today's date is 24-07, the user enters 2407, then it should navigate to another page i.e., second screen
First Screen: Passcode.dart
import 'package:flutter/material.dart';
import 'package:flutter_course/HomePage.dart';
//import 'package:pin_entry_text_field/pin_entry_text_field.dart';
import 'package:pin_code_text_field/pin_code_text_field.dart';
import 'package:intl/intl.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: homePage(),
));
}
}
class homePage extends StatefulWidget {
#override
_homePageState createState() => _homePageState();
}
class _homePageState extends State<homePage> {
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Stack(children: <Widget>[
Center(
child: Image.asset(
"assets/passcode.jpeg",
width: size.width,
height: size.height,
fit: BoxFit.fill,
),
),
Column(
children: <Widget>[
// SizedBox(height:200,),
// SizedBox(width: 300),
Padding(
padding: EdgeInsets.only(left: 460, top: 150),
child: Text("ENTER PASSCODE",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 38.0,
color: Colors.black)),
),
SizedBox(height: 30),
Padding(
padding: EdgeInsets.only(left: 460),
child: PinCodeTextField(
autofocus: false,
pinTextStyle: TextStyle(
color: Colors.black,
fontSize: 40,
fontWeight: FontWeight.bold),
hideCharacter: true,
maskCharacter: "*",
// highlight: true,
// highlightColor: Colors.blue,
defaultBorderColor: Colors.black,
hasTextBorderColor: Colors.white,
hasError: true,
errorBorderColor: Colors.red,
//onTextChanged: (String)=>func(context),
onDone: (String) => func(context),
),
),
],
)
]);
}
}
void func(context) {
var now = new DateTime.now();
var formatter = new DateFormat('MMMMd');
var formatted = formatter.format(now);
debugPrint(formatted);
if (String == formatted) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage()));
}
}
Second Screen :HomePage.dart
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTabController(length: 2,child:Scaffold(
drawer: Drawer(
child: Column(
children: <Widget>[
AppBar(
automaticallyImplyLeading: false,
title: Text('Choose'),
backgroundColor:Color(0xffedac51),
),
ListTile(
title: Text('Devices'),
onTap: () {
// Navigator.pushReplacement(
// context,
// MaterialPageRoute(
// builder: (BuildContext context) =>
// ProductsPage()));
},
),
ListTile(
title: Text('Allotted Devices'),
onTap: () {
// Navigator.pushReplacement(
// context,
// MaterialPageRoute(
// builder: (BuildContext context) =>
// ProductsPage()));
},
),
ListTile(
title: Text('Assign Devices'),
onTap: () {
// Navigator.pushReplacement(
// context,
// MaterialPageRoute(
// builder: (BuildContext context) =>
// ProductsPage()));
},
)
],
),
),
appBar: AppBar(
title: Text('Home'),
backgroundColor:Color(0xffedac51) ,
),
body: HomeBody()
)
);}
}
class HomeBody extends StatelessWidget{
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Stack(
children: <Widget>[
Center(
child: new Image.asset(
'assets/passcode.jpeg',
width: size.width,
height: size.height,
fit: BoxFit.fill,
),
),
Padding(
padding: EdgeInsets.only(top: 200, left: 500),
child: Column(
children: <Widget>[
Text("Let\'s Get Started!",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 38.0,
color: Colors.white)),
],
)),
],
);
}
}
When the passcode is entered as the current date in ddmm format, then it should navigate to the next screen
Not quite sure what you're trying to achieve, but something simple like this should do the trick:
DateTime today = DateTime.now();
String day, month, passCode;
if(today.day < 10){
day = "0" + today.day.toString();
} else {
day = today.day.toString();
}
if(today.month < 10){
month = "0" + today.month.toString();
} else {
month = today.month.toString();
}
passCode = day + month;