How to manually add items to listview in Flutter - 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]);
});
},
);

Related

Flutter - Package Tutorial not working when passing StreamBuilder in body

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

How to connect A ListTile to an Audio Widget in flutter

I want to connect 2 ListTiles together. I have a list of ListTiles that I created using ListView.builder.I have also an audio package that requires URLs to play the audio widget.
My ListView.Builder is like this:
ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
trailing: Icon(Icons.play_arrow),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Audio(),
),
);
},
);
},
),
My Audio Widget is like this:
I am using Audio Players package for Audio link is like this.
typedef OnError = void Function(Exception exception);
const kurl =
'https://download.quranicaudio.com/quran/mishaari_raashid_al_3afaasee/001.mp3';
const kurl2 =
'https://download.quranicaudio.com/quran/mishaari_raashid_al_3afaasee/002.mp3';
class Audio extends StatefulWidget {
#override
_AudioAppState createState() => _AudioAppState();
}
class _AudioAppState extends State<Audio> {
AudioPlayer advancedPlayer = AudioPlayer();
Widget remoteUrl() {
return SingleChildScrollView(
child: TabWrapper(
children: [
Text(
items.length.toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
),
PlayerWidget(url: kurl),
Text(
items.length.toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
),
PlayerWidget(url: kurl2),
],
),
);
}
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
StreamProvider<Duration>.value(
initialData: const Duration(),
value: advancedPlayer.onAudioPositionChanged,
),
],
child: DefaultTabController(
length: 1,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(text: 'Remote Url'),
],
),
title: const Center(
child: Text(
'Quran Audio',
style: TextStyle(fontSize: 30),
),
),
),
body: remoteUrl(),
),
),
);
}
}
My goal is that the ListTiles that I created When I click on one of them I will be taken to a separate page each containing I audio player widget which has a play button so I can listen to the audio afterwards.Any suggestions will be great. Any answers will be helpfull.
All you simply have to do is add an "Item" model class as a required property for the audio widget. I say "Item" but it's really whatever items[index] is.
Here's what it should look like in the Audio Widget Implementation:
class Audio extends StatefulWidget {
const Audio(this.item);
final /*Class Name of items[index]*/ item;
#override
_AudioAppState createState() => _AudioAppState();
}
class _AudioAppState extends State<Audio> {
AudioPlayer advancedPlayer = AudioPlayer();
Widget remoteUrl() {
return SingleChildScrollView(
child: TabWrapper(
children: [
Text(
widget.item.length.toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
),
PlayerWidget(url: kurl),
Text(
widget.item.length.toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
),
PlayerWidget(url: kurl2),
],
),
);
}
...
And then in the ListView.builder() simply pass in items[index].
ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
trailing: Icon(Icons.play_arrow),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Audio(items[index]),
),
);
},
);
},
),
...
I'm not 100% if this is the setup you're looking for, but if this doesn't work please provide a little more information on how you want it.

How to color the suggestions when the user is typing in flutter

I am using typeahead package in flutter to get suggestions to users as they type, what I want is to color the suggestions while the user is typing as its shouwn in the picture Colored suggestions while typing
Here is a simple example that am trying to implement
Main.dart
import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'CitiesService.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Colored suggestions Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Colored suggestions Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final myControllerCity = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Form(
key: this._formKey,
child: Padding(
padding: EdgeInsets.all(32.0),
child: Column(
children: <Widget>[
//SizedBox(height: 50,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: TypeAheadFormField(
textFieldConfiguration: TextFieldConfiguration(
controller: myControllerCity,
decoration: InputDecoration(labelText: 'City')),
suggestionsCallback: (pattern) {
return CitiesService.getSuggestionsCities(pattern);
},
itemBuilder: (context, suggestion) {
//
List<String> splitted_names_of_cities = suggestion
.toString()
.toLowerCase()
.split(myControllerCity.text);
final children = <Widget>[];
for (var i = 1;
i < splitted_names_of_cities.length;
i++) {
children.add(new ListTile(
title: Text.rich(
TextSpan(
children: [
TextSpan(
text: myControllerCity.text,
style: TextStyle(color: Colors.red),
),
TextSpan(text: splitted_names_of_cities[i]),
],
),
)));
}
print("this is the list $splitted_names_of_cities");
return new ListView(
children: children,
);
},
transitionBuilder: (context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (suggestion) {
myControllerCity.text = suggestion;
},
),
),
],
),
],
),
),
)),
);
}
}
And here is the function of the suggestions
static List<String> getSuggestionsCities(String query) {
List<String> wilayas = [];
algeria_cites.forEach((element) => wilayas.contains(element['wilaya_name_ascii']) ?
null : wilayas.add(element['wilaya_name_ascii']) );
wilayas.retainWhere((s) => s.toLowerCase().contains(query.toLowerCase()));
return wilayas;
}
In the previous code, for each item of the suggested cities name I was creating a full ListTile but I had to create TextSpan instead of that.
But each item has its specific length, for that reason I used List<InlineSpan>.
So here is the itemBuilder after fixing the error.
itemBuilder: (context, suggestion) {
List<InlineSpan> temp = [];
String suggestion_in_lower_case = suggestion.toString().toLowerCase();
List<String> splitted_names_of_cities = suggestion_in_lower_case.split(myControllerCity.text.toLowerCase());
for (var i = 0; i < splitted_names_of_cities.length-1; i++) {
if(splitted_names_of_cities.contains(myControllerCity.text.toLowerCase()));{
temp.add(
TextSpan(
text: splitted_names_of_cities[i],
style: TextStyle(
height: 1.0,
color: Colors.black,
),
),
);
temp.add(
TextSpan(
text: myControllerCity.text.toLowerCase(),
style: TextStyle(
color: Colors.red,
),
),
);
}
}
temp.add(
TextSpan(
text: splitted_names_of_cities.last,
style: TextStyle(
color: Colors.black,
),
),
);
return ListTile(
title: Text.rich(
TextSpan(
children: temp,
),
)
);
},
So it is working as expected, here is the demo.
https://i.stack.imgur.com/Tfs95.gif

Flutter - Find cards by names

I am new to flutter and I have a program that shows several cards and I have a question about how to make a card finder, I am using this code:
_card(
String phrase,
) {
return SliverToBoxAdapter(
child: Card(
margin: EdgeInsets.only(right: 50, left: 50, top: 20),
child: InkWell(
onTap: () {},
child: Column(children: <Widget>[
SizedBox(height: 15.0),
Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Text(
phrase,
style: TextStyle(
fontFamily: 'Circular',
fontSize: 17.0,
color: Colors.grey[800]),
),
),
SizedBox(height: 15.0),
]),
),
),
);
}
and I use this to make the various cards:
return Scaffold(
body: Stack(children: [
CustomScrollView(physics: BouncingScrollPhysics(), slivers: <Widget>[
_card('Abrir'),
_card('Alzar'),
_card('Aprender'),
_card('Caer'),
_card('Cerrar'),
_card('Cocinar'),
_card('Correr'),
_card('Cortar'),
_card('Enseñar'),
_card('Estar'),
_card('Hay'),
_card('Levantarse'),
_card('Mirar'),
_card('Oler'),
_card('Saltar'),
_card('Sentar'),
_card('Ser'),
_card('Tocar'),
_card('Tomar'),
_card('Tropezar'),
]),
]),
);
I really appreciate any help, thanks
Here is a solution using:
hooks_riverpod for State Management
fuzzy for fuzzy search
Full source code for easy copy-paste
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fuzzy/fuzzy.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
),
);
}
class HomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final phrases = useProvider(filteredPhrasesProvider);
return Scaffold(
body: ListView(
physics: BouncingScrollPhysics(),
children: [
TextField(
autofocus: true,
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Search',
),
onChanged: (value) =>
context.read(searchTermsProvider).state = value,
),
...phrases.map((phrase) => _Card(phrase: phrase)).toList(),
],
),
);
}
}
class _Card extends StatelessWidget {
final String phrase;
const _Card({
Key key,
this.phrase,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.all(10.0),
child: InkWell(
onTap: () {},
child: Padding(
padding: EdgeInsets.all(15.0),
child: Text(
phrase,
style: TextStyle(
fontFamily: 'Circular',
fontSize: 17.0,
color: Colors.grey[800],
),
),
),
),
);
}
}
final searchTermsProvider = StateProvider<String>((ref) => '');
final phrasesProvider = Provider<List<String>>(
(ref) => [
'Abrir',
'Alzar',
'Aprender',
'Caer',
'Cerrar',
'Cocinar',
'Correr',
'Cortar',
'Enseñar',
'Estar',
'Hay',
'Levantarse',
'Mirar',
'Oler',
'Saltar',
'Sentar',
'Ser',
'Tocar',
'Tomar',
'Tropezar',
],
);
final filteredPhrasesProvider = Provider<List<String>>((ref) {
final phrases = ref.watch(phrasesProvider);
final searchTerms = ref.watch(searchTermsProvider).state;
return searchTerms.isEmpty
? phrases
: Fuzzy<String>(phrases, options: FuzzyOptions(threshold: .4))
.search(searchTerms)
.map((result) => result.item)
.toList();
});
First you must change the logic of your code, create a List and then create the cards, so that the search engine works with the list
Create list:
final List<String> actions = ["Abrir", "Alzar", "Enseñar", "Sentar", "Mirar"];
Next, use List.generate or List.builder to create cards in the slivers
return Scaffold(
body: Stack(children: [
CustomScrollView(
physics: BouncingScrollPhysics(),
slivers: List.generate(actions.length, (i) => _cards(actions[i])
),
]),
);
Finally in your seacher, use this logic, the "contains" is optional, you can change the logic in the if
void search(String data) {
for(int i = 0; i < actions.length; i++) {
if(actions[i].contains(data)) {
print(actions[i]);
// In your case show card or add in another list to show after
}
}
}

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
),
),
),
);
}
}