Getting Error In Flutter : RangeError (index) : Invalid value: Not in inclusive range - flutter

I am flutter beginner and while practicing the Swipe to dismiss option I have completed the below mentioned code and after deleting few list items I am receiving the below error, I tried to solve the problem but couldn't,
import 'package:flutter/material.dart';
import 'dart:math' as math;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHome(),
);
}
}
class MyHome extends StatelessWidget {
final List<String> items = new List<String>.generate(30, (i) => "Items ${i+1}");
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Swipe To Dismiss"),
centerTitle: true,
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context,int index){
return Dismissible(
key: Key(items[index]),
onDismissed: (direction){
items.removeAt(index);
Scaffold.of(context).showSnackBar(new SnackBar(
content: Text("ITEM IS SUCCESSFULLY REMOVED")));
},
background: Container(
color: Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0),
),
child: ListTile(
title: Text("${items[index]}"),
),
);
}),
);
}
}
error while deleting list items and then scrolling down

Convert stateless widget into statefull and use setState so that ListView gets rebuilded.
Below code is tested & working. You can test it here.
import 'package:flutter/material.dart';
import 'dart:math' as math;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHome(),
);
}
}
class MyHome extends StatefulWidget {
#override
createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
final List<String> items =
new List<String>.generate(30, (i) => "Items ${i + 1}");
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Swipe To Dismiss"),
centerTitle: true,
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, int index) {
return Dismissible(
key: Key(items[index]),
onDismissed: (direction) {
items.removeAt(index);
Scaffold.of(context).showSnackBar(new SnackBar(
content: Text("ITEM IS SUCCESSFULLY REMOVED")));
setState((){});
},
background: Container(
color: Color((math.Random().nextDouble() * 0xFFFFFF).toInt())
.withOpacity(1.0),
),
child: ListTile(
title: Text("${items[index]}"),
),
);
}),
);
}
}

I have sucessfully fixed the issue . I converted MyHome from Stateless to StateFul Widget and added setState in onDismissed . Here is the changed code.
onDismissed: (direction){
setState(() {
items.removeAt(index);
});
Scaffold.of(context).showSnackBar(new SnackBar(
content: Text("ITEM IS SUCCESSFULLY REMOVED")));
},

Related

Where to write the network call in Flutter?

I have a BottomNavigationBar with 3 tabs. Consider I select a product in an e-commerce app from the pages inside the first BottomNavigationBarItem. I need to see that product in the second BottomNavigationBarItem(cart page). I have written the network call code in initState() of second BottomNavigationBarItem; but it will not be called when I go to that page and I can't see the recently added product to the cart. Is it better to write them in the build method itself? Writing them in the build method calls it every time I go to other tabs also.
Use FutureBuilder or StreamBuilder to network call and flow the data to UI
Hope this will help you
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedPage = 0;
String _selectedProduct;
Widget getCurrentPage(){
switch(_selectedPage){
case 0:
return Page1((selectedProduct){
setState((){
this._selectedProduct = selectedProduct;
_selectedPage=1;
});});
case 1:
return Page2(this._selectedProduct);
case 2:
return Page3();
default:
return Center(child:Text('Error'));
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: getCurrentPage(),
bottomNavigationBar: BottomNavigationBar(
onTap: (index){
setState((){
_selectedPage = index;
});
},
currentIndex: _selectedPage,
items: ['tab 1', 'tab 2', 'tab3'].map((e)=>BottomNavigationBarItem(
icon: Container(),
title: Text(e),
)).toList(),),
);
}
}
class Page1 extends StatelessWidget {
final Function(String) onProductClick;
const Page1(this.onProductClick);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text('Page 1')),
body:Column(
children: <Widget>[
RaisedButton(
child: Text('Product 1'),onPressed: ()=>onProductClick('Product 1'),),
RaisedButton(
child: Text('Product 2'),onPressed: ()=>onProductClick('Product 2'),),
RaisedButton(
child: Text('Product 3'),onPressed: ()=>onProductClick('Product 3'),),
RaisedButton(
child: Text('Product 4'),onPressed: ()=>onProductClick('Product 4'),),
RaisedButton(
child: Text('Product 5'),onPressed: ()=>onProductClick('Product 5'),),
],)
);
}
}
class Page2 extends StatelessWidget {
final String selectedProduct;
const Page2(this.selectedProduct);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text('Page 2')),
body:Center(child:Text(selectedProduct??'Nothing selected'))
);
}
}
class Page3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text('Page 3')),
body:Center(child:Text('Page 3'))
);
}
}

How to create user history page similar to 'my activity' on google - flutter

I am trying to make a history page in flutter. When I press 'a','b' or 'c' in my homepage, I want it to show what I pressed and the date I pressed the text on my history page similar to 'my activity' on google. This is what I came up with so far, and I don't even know if it is the best way to make it. It also has an error
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int count = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
Tile(text: Text("a")),
Tile(text: Text("b")),
Tile(text: Text("c")),
],
));
}
}
int count = 0;
class Tile extends StatefulWidget {
final Text text;
Tile({this.text});
#override
TileState createState() => TileState();
}
class TileState extends State<Tile> {
#override
Widget build(BuildContext context) {
return ListTile(
title: widget.text,
onTap: () {
count++;
print(count);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HistoryPage()),
);
},
);
}
}
class HistoryPage extends StatefulWidget {
#override
HistoryPageState createState() => HistoryPageState();
}
class HistoryPageState extends State<HistoryPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
})),
body: ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(text),
);
},
),
);
}
}
How should I make my user history page?
You can copy paste run full code below
You can put your click event in a History List and use ListView to show this History List
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int count = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
Tile(text: Text("a")),
Tile(text: Text("b")),
Tile(text: Text("c")),
],
));
}
}
int count = 0;
List<History> historyList = [];
class History {
String data;
DateTime dateTime;
History({this.data, this.dateTime});
}
class Tile extends StatefulWidget {
final Text text;
Tile({this.text});
#override
TileState createState() => TileState();
}
class TileState extends State<Tile> {
#override
Widget build(BuildContext context) {
return ListTile(
title: widget.text,
onTap: () {
count++;
print(count);
historyList
.add(History(data: widget.text.data, dateTime: DateTime.now()));
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HistoryPage(),
));
},
);
}
}
class HistoryPage extends StatefulWidget {
#override
HistoryPageState createState() => HistoryPageState();
}
class HistoryPageState extends State<HistoryPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
})),
body: ListView.builder(
itemCount: historyList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
' ${historyList[index].data} ${historyList[index].dateTime.toString()}'),
);
},
),
);
}
}

How to make webview not reload when I switch appbar in my flutter app?

I want webview not reload when I switch appbar in my flutter app, but I don't know how should I do, and I am sorry that I am a beginner.
This is my recorded gif:
I searched on Google, but I didn't find an answer related to this.
//index.dart
import 'package:flutter/material.dart';
import 'navigation_tab.dart';
import '../home/home_page.dart';
import '../market/market_page.dart';
import '../my/my_page.dart';
class Index extends StatefulWidget {
#override
_IndexState createState() => new _IndexState();
}
class _IndexState extends State<Index> with TickerProviderStateMixin {
int _currentIndex = 0;
List<NavigationTab> _navigationTabs;
List<StatefulWidget> _pageList;
StatefulWidget _currentPage;
#override
void initState() {
super.initState();
_navigationTabs = <NavigationTab>[
new NavigationTab(icon: new Icon(Icons.account_balance), title: new Text("home"), vsync: this),
new NavigationTab(icon: new Icon(Icons.local_mall), title: new Text("market"), vsync: this),
new NavigationTab(icon: new Icon(Icons.account_box), title: new Text("my"), vsync: this),
];
_pageList = <StatefulWidget>[
new HomePage(),
new MarketPage(),
new MyPage(),
];
_currentPage = _pageList[_currentIndex];
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: _currentPage,
bottomNavigationBar: new BottomNavigationBar(
items: _navigationTabs.map((tab) => tab.item).toList(),
currentIndex: _currentIndex,
fixedColor: Colors.blue,
type: BottomNavigationBarType.fixed,
onTap: (int index) {
setState(() {
_currentIndex = index;
_currentPage = _pageList[index];
});
},
),
);
}
}
//home_page.dart
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: PreferredSize(
child: new AppBar(
title: new Text("home"),
centerTitle: true,
),
preferredSize: Size.fromHeight(40)
),
body: new Center(
child: new Text("this is home page", style: TextStyle(fontSize: 36)),
),
);
}
}
//market_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
class MarketPage extends StatefulWidget {
#override
_MarketPageState createState() => new _MarketPageState();
}
class _MarketPageState extends State<MarketPage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: PreferredSize(
child: new AppBar(
title: new Text("market"),
centerTitle: true,
),
preferredSize: Size.fromHeight(40)
),
body: new WebviewScaffold(
url: "https://flutter.dev/",
withLocalStorage: true,
withJavascript: true
),
);
}
}
I want webview page keepalive, like vue, How should I do it?
Basically, your MarketPage widget is re-building whenever you open it. You can use keep alive to attain your required behaviour.
//market_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
class MarketPage extends StatefulWidget {
#override
_MarketPageState createState() => new _MarketPageState();
}
class _MarketPageState extends State<MarketPage> with AutomaticKeepAliveClientMixin{
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: PreferredSize(
child: new AppBar(
title: new Text("market"),
centerTitle: true,
),
preferredSize: Size.fromHeight(40)
),
body: new WebviewScaffold(
url: "https://flutter.dev/",
withLocalStorage: true,
withJavascript: true
),
);
}
#override
bool get wantKeepAlive => true;
}
Update -
Here is an example of how you can do it using AutomaticKeepAliveClientMixin. This is working fine for me. I'm using Pageview and webview_flutter instead of flutter_webview_plugin.
main.dart
import 'package:flutter/material.dart';
import 'package:webview_project/pag1.dart';
import 'package:webview_project/page2.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
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> {
int _currentIndex = 0;
var controller = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: PageView(
physics: NeverScrollableScrollPhysics(),
controller: controller,
children: <Widget>[
Page1(),
Page2(),
],
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.web), title: Text('Web')),
],
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
controller.jumpToPage(index);
});
},
),
);
}
}
page1.dart
import 'package:flutter/material.dart';
class Page1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Text('Page1'),
);
}
}
page2.dart
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class Page2 extends StatefulWidget {
#override
_Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2>
with AutomaticKeepAliveClientMixin<Page2> {
#override
Widget build(BuildContext context) {
return WebView(
initialUrl: 'https://www.flutter.dev/',
);
}
#override
bool get wantKeepAlive => true;
}

How to keep the widget's state in Scaffold.drawer in Flutter?

I want to keep the widget's state in Scaffold.drawer. The Scaffold.drawer is a custom widget, which has a RaiseButton in it.
When click the button, the text in the button changed.
But when the drawer is closed, and reopen the drawer, the changed text is reseted.
I have use " with AutomaticKeepAliveClientMixin<> " in my custom Drawer, but it does't work.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Demo"),
),
drawer: Drawer(child: CustomDrawer(),),
body: Center(
child: Text("Flutter Demo"),
),
);
}
}
class CustomDrawer extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _CustomDrawerState();
}
}
class _CustomDrawerState extends State<CustomDrawer> with AutomaticKeepAliveClientMixin<CustomDrawer> {
String btnText = "Click!";
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context);
return Center(
child: RaisedButton(onPressed: () {
setState(() {
btnText = "Clicked!!";
});
}, child: Text(btnText),),
);
}
}
I expect the widget's state can keep, even if the Drawer is closed.
Create a separate widget for the drawer and just use in anywhere you need to.
Manage the Drawer State with a Provider
class DrawerStateInfo with ChangeNotifier {
int _currentDrawer = 0;
int get getCurrentDrawer => _currentDrawer;
void setCurrentDrawer(int drawer) {
_currentDrawer = drawer;
notifyListeners();
}
void increment() {
notifyListeners();
}
}
Adding State Management to the Widget tree
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MultiProvider(
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
),
providers: <SingleChildCloneableWidget>[
ChangeNotifierProvider<DrawerStateInfo>(
builder: (_) => DrawerStateInfo()),
],
);
}
}
Creating The Drawer Widget for reuse in application
class MyDrawer extends StatelessWidget {
MyDrawer(this.currentPage);
final String currentPage;
#override
Widget build(BuildContext context) {
var currentDrawer = Provider.of<DrawerStateInfo>(context).getCurrentDrawer;
return Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text(
"Home",
style: currentDrawer == 0
? TextStyle(fontWeight: FontWeight.bold)
: TextStyle(fontWeight: FontWeight.normal),
),
trailing: Icon(Icons.arrow_forward),
onTap: () {
Navigator.of(context).pop();
if (this.currentPage == "Home") return;
Provider.of<DrawerStateInfo>(context).setCurrentDrawer(0);
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) =>
MyHomePage(title: "Home")));
},
),
ListTile(
title: Text(
"About",
style: currentDrawer == 1
? TextStyle(fontWeight: FontWeight.bold)
: TextStyle(fontWeight: FontWeight.normal),
),
trailing: Icon(Icons.arrow_forward),
onTap: () {
Navigator.of(context).pop();
if (this.currentPage == "About") return;
Provider.of<DrawerStateInfo>(context).setCurrentDrawer(1);
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => MyAboutPage()));
},
),
],
),
);
}
}
Use of Drawer in one of your pages
class MyAboutPage extends StatefulWidget {
#override
_MyAboutPageState createState() => _MyAboutPageState();
}
class _MyAboutPageState extends State<MyAboutPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('About Page'),
),
drawer: MyDrawer("About"),
);
}
}
In your case, you have 2 choices:
You should keep your state in your Top level widget. in your case _MyHomePageState;
Use state managers like Redux, Bloc, ScopedModel. I think ScopedModel is great for you in this case.
otherwise, you can't control the state of Drawer. cause it re-creates every moment you call the Drawer by the action button in Appbar;

Proper page navigation

I am trying to navigate to a page called contactView. I have made a list of contacts and I wait to navogate to a contact when I click on there name. This is what I have so far. I am stuck trying to get the navigation to work. Any help would be great.
class ContactList extends StatelessWidget {
final List<Contact> _contacts;
ContactList(this._contacts);
#override
Widget build(BuildContext context) {
return new ListView.builder(
padding: new EdgeInsets.symmetric(vertical: 8.0),
itemBuilder: (context, index) {
return new _ContactListItem(_contacts[index]);
Navigator.push(context, MaterialPageRoute(builder: (context) => viewContact())
);
},
itemCount: _contacts.length,
);
}
}
Here are few things that I can immediately point out (Problems):
onPressed is not available on ListView.builder() , you may check
here:
https://docs.flutter.io/flutter/widgets/ListView/ListView.builder.html
Navigator.push(context, MaterialPageRoute(builder: (context) => viewContact()) this won't execute because it is after return
Suggestions:
You might need to wrap your _ContactListItem() inside a
GestureDetector and implement an onTap callback
Sample Code:
class ContactList extends StatelessWidget {
final List<Contact> _contacts;
ContactList(this._contacts);
#override
Widget build(BuildContext context) {
return ListView.builder(
padding: EdgeInsets.symmetric(vertical: 8.0),
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
//TODO: Insert your navigation logic here
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) =>
ContactView(_contacts[index])));
},
child: _ContactListItem(_contacts[index]),
);
},
itemCount: _contacts.length,
);
}
}
Another option could be to change the implementation of
_ContactListItem() and may be use a ListTile and implement an onTap in ListTile, you can find it here: https://docs.flutter.io/flutter/material/ListTile-class.html
You may also try to implement named routes, here is a tutorial for
that https://flutter.io/cookbook/networking/named-routes/
I hope this was helpful in someway, let me know if I misinterpreted the question.
See if the below is what you're looking for.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Contact Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Contact 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 _contacts = [
Contact(name: 'John'),
Contact(name: 'Mary'),
Contact(name: 'Suzy')
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
title: const Text(
'Contact Demo',
style: const TextStyle(color: Colors.white),
),
),
body: ListView.builder(
itemCount: _contacts.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text('Contact #$index'),
onTap: () {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) =>
ContactView(contact: _contacts[index]),
));
},
);
},
),
);
}
}
class Contact {
Contact({this.name});
final String name;
}
class ContactView extends StatelessWidget {
ContactView({this.contact});
final Contact contact;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(contact.name),
),
body: Center(
child: Text(contact.name),
),
);
}
}