Flutter: UI and Codes not updating - android

I'm just a student try to make school project and don't know codding very well. I stuck in somewhere, everything was just fine but then flutter stopped updating my codes in home.dart file. I update my codes change some variables but it does not working, it uses the old code. But other .dart files is working and getting update. I sent the code, I changed AppBar part but its not updating. and I'm getting an error from old code.
class _HomeState extends State<Home> {
List<PopularTourModel> popularTourModels = new List();
List<CountryModel> country = new List();
#override
void initState() {
country = getCountrys();
popularTourModels = getPopularTours();
super.initState();
}
#override
void didUpdateWidget(oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget != widget) {
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Samsun Tur'),
actions: [
],
elevation: 0.0,
),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"BETA",
style: TextStyle(
fontSize: 28,
color: Colors.black54,
fontWeight: FontWeight.w600),
),
SizedBox(
height: 8,
),
Text(
"Tarihi Mekanlar:",
style: TextStyle(
fontSize: 20,
color: Colors.black54,
fontWeight: FontWeight.w600),
),
SizedBox(
height: 16,
),
GestureDetector(
onTap: () {
print('ÇALIŞTI, mı acaba?');
},
child: Container(
height: 240,
child: ListView.builder(
itemCount: country.length,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemBuilder: (context, index)
{
return CountryListTile(
label: country[index].label,
countryName: country[index].countryName,
noOfTours: country[index].noOfTours,
rating: country[index].rating,
imgUrl: country[index].imgUrl,
);
}),
),
),
SizedBox(
height: 8,
),
Text(
"Size en yakın yerler!",
style: TextStyle(
fontSize: 20,
color: Colors.black54,
fontWeight: FontWeight.w600),
),
SizedBox(
height: 16,
),
ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: popularTourModels.length,
itemBuilder: (context, index) {
return PopularTours(
desc: popularTourModels[index].desc,
imgUrl: popularTourModels[index].imgUrl,
title: popularTourModels[index].title,
price: popularTourModels[index].price,
rating: popularTourModels[index].rating,
mekan: popularTourModels[index].mekan,
desclong: popularTourModels[index].desclong,
latitude: popularTourModels[index].latitude,
longitude: popularTourModels[index].longitude,
distanceToUser: popularTourModels[index].distanceToUser,
);
})
],
),
),
),
);
}
}
════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Could not find a generator for route RouteSettings("lib/views/home", null) in the _WidgetsAppState.
Make sure your root app widget has provided a way to generate
this route.
Generators for routes are searched for in the following order:
1. For the "/" route, the "home" property, if non-null, is used.
2. Otherwise, the "routes" table is used, if it has an entry for the route.
3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
4. Finally if all else fails onUnknownRoute is called.
Unfortunately, onUnknownRoute was not set.
When the exception was thrown, this was the stack:
#0 _WidgetsAppState._onUnknownRoute.<anonymous closure> (package:flutter/src/widgets/app.dart:1175:9)
#1 _WidgetsAppState._onUnknownRoute (package:flutter/src/widgets/app.dart:1190:6)
#2 NavigatorState._routeNamed (package:flutter/src/widgets/navigator.dart:3388:36)
#3 NavigatorState.pushNamed (package:flutter/src/widgets/navigator.dart:3425:20)
#4 NavigatorState.popAndPushNamed (package:flutter/src/widgets/navigator.dart:3479:12)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#39fcc
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(26.9, 51.3)
finalLocalPosition: Offset(26.9, 27.3)
button: 1
sent tap down
════════════════════════════════════════════════════════════════════════════════════════════════════
Lost connection to device.

Related

Flutter How to make a pagination from streambuilder with firestore (lazy loading)

Hello please I am new in flutter mobile devellopement. I would like to do a pagination (Lazy loading from streambuilder with firestore). Indeed when I do a stream all the documents load and it takes a long time and also my application sometimes bugs (maybe because I loaded a lot of data in memory). I would like to simplify things by using a pagination but I don't really know how to do it. or you can load 10 documents per call. please help me find a solution to avoid bugging my application and load less document per call. here is the full code of the feed part
class FeedJob extends StatefulWidget {
FeedJob({Key? key}) : super(key: key);
#override
_FeedJobState createState() => _FeedJobState();
}
class _FeedJobState extends State<FeedJob> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("job_feed")
.orderBy("time", descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return Column(
children: [
Expanded(
flex: 0,
child: Column(children: [
TiTle(title: "Feeds"),
])),
Expanded(
child: ListView(
children: [
ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: snapshot.data!.docs.map((e) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Column(
children: [
ListTile(
leading: Container(
width: 40,
height: 40,
alignment: Alignment.topCenter,
decoration: BoxDecoration(
image: DecorationImage(
alignment:
Alignment.topCenter,
fit: BoxFit.cover,
image:
CachedNetworkImageProvider(
e.get(
'photo'))),
color: Colors.blue
.withOpacity(.2),
borderRadius:
BorderRadius.all(
Radius.circular(
20))),
),
trailing: Column(
children: [
Icon(Icons.comment_rounded,
size: 15,
color: Colors.grey),
Text("comment".tr,
style: TextStyle(
fontSize: 8,
color: Colors.grey))
],
),
title: Text(e.get('name'),
style: TextStyle(
color: Colors.black,
fontSize: 10,
fontWeight:
FontWeight.bold)),
subtitle:
Text(e.get('time').toString(),
style: TextStyle(
fontSize: 8,
color: Colors.grey,
)),
),
Padding(
padding: const EdgeInsets.only(
left: 5.0,
right: 8,
bottom: 15),
child: Text(
e.get('description'),
textAlign: TextAlign.justify,
),
)
],
),
),
)
],
);
}).toList()),
],
),
),
],
);
}
}));
}
}
You can use startAfterDocument to tell Firestore what was the last document you fetched (assuming you keep a reference to it each time).
// Prepare the query.
final List<JobModel> fetchedData = [];
final int firstBatchSize = 6;
final int nextBatchSize = 12;
DocumentSnapshot<JobModel>? lastDocument;
final Query<DestinationModel> query = FirebaseFirestore.instance
.collection('jobs')
.orderBy('time', descending: true)
.withConverter<JobModel>(
fromFirestore: (snapshot, _) => JobModel.fromFirestore(snapshot),
toFirestore: (JobModel job, _) => job.toFirestore(),
);
// Set the starting point of the query.
if (lastDocument != null) query.startAfterDocument(lastDocument);
// Set the limit for the query.
query.limit(fetchedData.isEmpty ? firstBatchSize : nextBatchSize);
// Run the query.
final QuerySnapshot<JobModel> results = await query.get();
// Do something with the results; Store the last document fetched.

'child == _child': is not true , Duplicate GlobalKey detected in widget tree

I am getting this error when I render a child component in flutter.
Failed assertion: line 6075 pos 12: 'child == _child': is not true.
Duplicate GlobalKey detected in widget tree.
A RenderShrinkWrappingViewport expected a child of type RenderSliver but received a child of type RenderFlex.
my code is here.........
// #dart=2.9
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_project/constants.dart';
import 'package:flutter_project/provider/store_provider.dart';
import 'package:flutter_project/services/store_services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:paginate_firestore/bloc/pagination_listeners.dart';
import 'package:paginate_firestore/paginate_firestore.dart';
import 'package:provider/provider.dart';
class NearByStore extends StatefulWidget {
#override
_NearByStoreState createState() => _NearByStoreState();
}
class _NearByStoreState extends State<NearByStore> {
StoreServices _storeServices = StoreServices();
PaginateRefreshedChangeListener refreshedChangeListener = PaginateRefreshedChangeListener();
#override
Widget build(BuildContext context) {
final _storeData = Provider.of<StoreProvider>(context);
_storeData.getUserLocationData(context);
String getDistance(location) {
var distance = Geolocator.distanceBetween(
_storeData.userLatitude, _storeData.userLongitude, location.latitude,
location.longitude);
var distanceInKm = distance / 1000;
return distanceInKm.toStringAsFixed(2);
}
return Container(
child: StreamBuilder<QuerySnapshot>(
stream: _storeServices.getTopPickedStore(), // will change it soon
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>snapShot) {
if (!snapShot.hasData) return
CircularProgressIndicator();
List shopDistance = [];
for (int i = 0; i <= snapShot.data.docs.length - 1; i++) {
var distance = Geolocator.distanceBetween(
_storeData.userLatitude, _storeData.userLongitude,
snapShot.data.docs[i]['location'].latitude,
snapShot.data.docs[i]['location'].longitude);
var distanceInKm = distance / 1000;
shopDistance.add(distanceInKm);
}
shopDistance
.sort(); // this will sort with nearest distance. if nearest distance is more than 10, that means no shop near by;
if (shopDistance[0] > 10) {
return Container(
child: Stack(
children: [
Center(
child: Text('***That all folks***',
style: TextStyle(color: Colors.grey),),
),
Image.asset(
'images/city.png', color: Colors.black12),
Positioned(
right: 10.0,
top: 80,
child: Container(
width: 100,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Made by : ', style: TextStyle(
color: Colors.black54
),),
Text('VOID TECHNOLOGY', style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Anton',
letterSpacing: 2,
color: Colors.grey
),)
],
),
),
)
],
),
);
}
return Padding(
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RefreshIndicator(
child: PaginateFirestore(
bottomLoader: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Theme
.of(context)
.primaryColor),
),
header: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(
left: 8, right: 8, top: 20
),
child: Text('All Nearby Stores',
style: TextStyle(fontWeight: FontWeight.w900,
fontSize: 18
),),
),
Padding(
padding: const EdgeInsets.only(
left: 8, right: 8, bottom: 10
),
child: Text('Findout quality products near you',
style: TextStyle(
fontSize: 12, color: Colors.grey
),),
),
],
),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilderType: PaginateBuilderType.listView,
itemBuilder: (index, context, document) =>
Padding(
padding: const EdgeInsets.all(4),
child: Container(
width: MediaQuery
.of(context)
.size
.width,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 100,
height: 110,
child: Card(
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.network(document['imageUrl'],
fit: BoxFit.cover,
),
),
),
),
SizedBox(width: 10,),
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
child: Text(
document['shopName'], style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
SizedBox(
height: 3,
),
Text(document['dialog'],
style: kStoreCardStyle,),
SizedBox(
height: 3,
),
Container(
width: MediaQuery
.of(context)
.size
.width - 250,
child: Text(document['address'],
overflow: TextOverflow.ellipsis,
style: kStoreCardStyle,
),
),
SizedBox(
height: 3,
),
Text(
'${getDistance(document['location'])}Km',
overflow: TextOverflow.ellipsis,
),
SizedBox(
height: 3,
),
Row(
children: [
Icon(
Icons.star,
size: 12,
color: Colors.grey,
),
SizedBox(
width: 4,
),
Text('3.2', style: kStoreCardStyle,)
],
)
],
)
],
),
),
),
query: FirebaseFirestore.instance.collection('vendors')
.where('accVerified', isEqualTo: true)
.where('isTopPicked', isEqualTo: true).orderBy(
'shopName'),
listeners: [
refreshedChangeListener,
],
footer: Padding(
padding: const EdgeInsets.only(top: 30),
child: Container(
child: Stack(
children: [
Center(
child: Text('***That all folks***',
style: TextStyle(color: Colors.grey),),
),
Image.asset(
'images/city.png', color: Colors.black12),
Positioned(
right: 10.0,
top: 80,
child: Container(
width: 100,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Made by : ', style: TextStyle(
color: Colors.black54
),),
Text('VOID TECHNOLOGY', style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Anton',
letterSpacing: 2,
color: Colors.grey
),)
],
),
),
)
],
),
),
),
),
onRefresh: () async {
refreshedChangeListener.refreshed = true;
},
)
],
),
);
},
),
);
}
}
======== Exception caught by widgets library =======================================================
The following assertion was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#a5a30](state: RawGestureDetectorState#b8caf(gestures: <none>, behavior: opaque)):
'package:flutter/src/widgets/framework.dart': Failed assertion: line 6075 pos 12: 'child == _child': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
The relevant error-causing widget was:
PaginateFirestore file:///E:/Flutter%20Main/flutter_project/lib/widgets/near_by_store.dart:99:26
When the exception was thrown, this was the stack:
#2 SingleChildRenderObjectElement.forgetChild (package:flutter/src/widgets/framework.dart:6075:12)
#3 Element._retakeInactiveElement (package:flutter/src/widgets/framework.dart:3563:14)
... Normal element mounting (10 frames)
#13 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14)
#14 Element.updateChild (package:flutter/src/widgets/framework.dart:3360:20)
======== Exception caught by widgets library =======================================================
The following assertion was thrown while finalizing the widget tree:
Duplicate GlobalKey detected in widget tree.
The following GlobalKey was specified multiple times in the widget tree. This will lead to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the previous instance is moved to the new location. The key was:
- [GlobalKey#4acc7]
This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.
The specific parent that did not update after having one or more children forcibly removed due to GlobalKey reparenting is:
- Semantics(container: false, properties: SemanticsProperties, label: null, value: null, hint: null, hintOverrides: null, renderObject: RenderSemanticsAnnotations#faf5c NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED)
A GlobalKey can only be specified on one widget at a time in the widget tree.
When the exception was thrown, this was the stack:
#0 BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:2900:15)
#1 BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:2925:8)
#2 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:877:19)
#3 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#4 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
...
====================================================================================================
The header and footer properties are expected to be Slivers. so in order to use non-sliver widgets, you can wrap them with SliverToBoxAdapter which is "a sliver that contains a single box widget."
Try like this.
Update the Header code to:
header: SliverToBoxAdapter(
child: Column(
...
),
),
And update the footer code to:
footer: SliverToBoxAdapter(
child: Padding(
...
)
),

Problem with getting access to index of a map in flutter

I have a map<string, dynamic> ,and want to show it's components in cards by ListView.Builder, but the problem is by getting access to this map's indexes..
When running the app, it return "null" in the card!!
I have tried many solutions that I saw in StackOverFlow for a similar issues, but without a result.
Here where I identified my map:
var _item;
List listCount = [];
Map<String, dynamic> records = {};
String name;
And here where I give the var _item it's value:
MyCard(
colour: Colors.lightBlueAccent,
maker: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamBuilder<int>(
stream: _stopWatchTimer2.rawTime,
initialData: 0,
builder: (context, snap) {
final value = snap.data;
final displayTime = StopWatchTimer.getDisplayTime(
value,
hours: _isHours2);
_item = displayTime;
return Padding(
padding: EdgeInsets.all(5.0),
child: Text(displayTime,
style: TextStyle(
fontSize: 30.0, color: Colors.white)),
);
},
),
],
),
),
And here in the "Save" button I give the 1st parameter of the map and assign in name variable:
createAlertDialog(buildContext, context) {
TextEditingController controller;
return showDialog(
context: context,
// barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: Text(
'Type record name',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18.0),
),
content: TextField(
controller: controller,
onChanged: (value) {
name = value;
}),
actions: [
MaterialButton(
elevation: 5.0,
child: Text('Save'),
onPressed: () {
listCount.add(_item);
print(_item);
records[name] = _item;
print(records);
Navigator.pop(context);
},
),
MaterialButton(
elevation: 5.0,
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
}
Finally here where I tried to show it in a card by listview.builder:
Container(
color: Colors.white,
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: records.length,
itemBuilder: (context, index) {
return MyCard(
colour: Colors.cyanAccent,
maker: Container(
width: 250.0,
height: 75.0,
child: Text(
'${records[index]}',
style: TextStyle(fontSize: 25.0),
textAlign: TextAlign.center,
),
),
);
},
),
),
I think the problem with the 2nd parameter of itemBuilder which it (index) because I replaced this keyword with another one randomly, and get the same result when running my app "Null".
This screenShot explain the problem:
You can get map entries as List as such:
final recordsEntries = records.entries.toList()
Then, you have a List of MapEntry and are able to access key and value associated for each item of the collection.
recordsEntries[index].key
recordsEntries[index].value

RangeError (index): Invalid value: Not in range 0..3, inclusive: 4 in Flutter

I am getting a range error while running my code.
I just want to show the items on my home screen but it is showing an error. Please help me. Thank you very much in advance. I don't know where I am getting this error. Here is my error output.
Exception caught by widgets library ═══════════════════════════════════════════════════════
The following RangeError was thrown building HomeScreen(dirty, dependencies: [MediaQuery, _InheritedTheme, _LocalizationsScope-[GlobalKey#4b453]]):
RangeError (index): Invalid value: Not in range 0..3, inclusive: 4
The relevant error-causing widget was:
HomeScreen file:///C:/Project/ur_info/lib/WelcomeScreen/WelcomeScreen.dart:56:45
When the exception was thrown, this was the stack:
#0 List.[] (dart:core-patch/growable_array.dart:146:60)
#1 HomeScreen.build (package:urinfo/Home/home.dart:72:45)
#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4576:28)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
...
Here is My Code
Home.Dart
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:urinfo/Home/items.dart';
import 'Events.dart';
import 'categories.dart';
class HomeScreen extends StatelessWidget {
final url;
final Events events;
const HomeScreen({Key key, this.url, this.events}) : super(key: key);
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return SafeArea(
child: Scaffold(
backgroundColor: Colors.pink[50],
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.pink[50]
),
child: Padding(
padding: EdgeInsets.only(left: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: size.height*0.05 ),
Center(
child: RichText(
text: TextSpan(
style: Theme.of(context).textTheme.headline5,
children: [
TextSpan(text: "Hello Welcome Back Pratul", style: TextStyle(fontWeight: FontWeight.bold))
]
),
),
),
SizedBox(height: 10),
Center(child: Text("Categories", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.indigo),)),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: EdgeInsets.only(top: 10),
child: Row(
children: <Widget>[
Categories (
name: "Btech", imageurl: "assets/icons/Btech.svg",),
Categories (
name: "BA Hons.", imageurl: "assets/icons/Bahons.svg",),
Categories (
name: "Pharmacy", imageurl: "assets/icons/nursing.svg",),
Categories (
name: "Business", imageurl: "assets/icons/Business.svg",),
],
),
),
),
SizedBox(height: size.height*.12,),
Center(child: Text("Upcomming Events", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.indigo),)),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.only(top: 15, right: 10),
child: Row(
children: <Widget>[
Events(item: items[items.length]),
SizedBox(width: 15)],
),
),
)
],
),
),
),
),
),
);
}
}
Events.Dart
import 'package:flutter/material.dart';
import 'package:urinfo/webview.dart';
import 'items.dart';
class Events extends StatelessWidget {
final Item item;
const Events({Key key, this.item}) : super(key: key);
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=> Webview()));
},
child: Container(
width: 120,
height: 170,
child: Stack(
children: <Widget>[
Container(
height: 150,
decoration: BoxDecoration(
color: item.color,
borderRadius: BorderRadius.circular(20)
),
),
Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20)
),
child: Padding(
padding: const EdgeInsets.only(top: 5, left: 5, right: 5),
child: Image.asset(item.imageurl, fit: BoxFit.cover, width: 100,),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(child: Text(item.name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, color: Colors.white),)),
)
],
),
],
),
),
);
}
}
Items.dart
import 'package:flutter/material.dart';
class Item {
final String imageurl, name, weburl;
final int id;
final Color color;
Item({this.color, this.imageurl, this.name, this.weburl, this.id});
}
List<Item> items=[
Item(
id: 0,
imageurl: "assets/images/Dexterix.jpg",
name: "Dexterix",
weburl: "https://dexterix.tech/",
color: Colors.black,
),
Item(
id: 1,
imageurl: "assets/images/space apps.jpg",
name: "Space Apps",
weburl: "https://dexterix.tech/",
color: Colors.black,
),
Item(
id: 2,
imageurl:"assets/images/books.jpg",
name: "Books Show",
weburl: "https://dexterix.tech/",
color: Colors.yellow[200],
),
Item(
id: 3,
imageurl: "assets/images/SIH.png",
name: "SIH",
weburl: "https://dexterix.tech/",
color: Colors.white10,
),
];
WelcomeScreen.dart
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:introduction_screen/introduction_screen.dart';
import '../Home/home.dart';
class WelcomeScreen extends StatefulWidget {
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
List<PageViewModel> getPages() {
return [
PageViewModel(
image: Image.asset("assets/images/Welcom.png"),
title: ('Welcome To Ur Info'),
body: "Your Own Info App",
footer: Text("Lets Get Started"),
decoration: PageDecoration(pageColor: Colors.lightBlue[50])
),
PageViewModel(
image: Image.asset("assets/images/Exams.png"),
title: ('Get Your Exams Details'),
body: "Download your admit cards & other details",
footer: Text(""),
decoration: PageDecoration(pageColor: Colors.green[100])
), PageViewModel(
image: Image.asset("assets/images/Events.png"),
title: ('Track all the upcomming Events'),
body: "No need to worry about events",
footer: Text(""),
decoration: PageDecoration(pageColor: Colors.yellow[50])
), PageViewModel(
image: Image.asset("assets/images/study.png"),
title: ('Daily Feeds on Exams & Syllabus'),
body: "Provides daily news related to education",
footer: Text(""),
),
];
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: IntroductionScreen(
globalBackgroundColor: Colors.pink[50],
pages: getPages(),
onSkip: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomeScreen()
));
},
onDone: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomeScreen()
));
},
showSkipButton: true,
showNextButton: true,
dotsDecorator: DotsDecorator(
color: Colors.pink,
activeColor: Colors.blueAccent[700],
),
dotsFlex: 1,
skip: Text('Skip'),
next: Text('Next'),
done: Text('Get Started'),
)
),
);
}
}
items.length == 4 while lists always start at an index of 0. Therefore it will try to find an item of index 1 to index of 4. I recommend using items.length - 1.
I found a trick that works for me, when facing the RangeError (index) error: Invalid value: Not in range 0..3, inclusive: 4 in Flutter.
Apparently it happens that the scrolling attached to the listview goes too fast to the point of exceeding the length of the array by one unit.
First I add itemCount: items.length, then in itemBuilder and before the return I insert this: if (index> = items.length) {return const Offstage (); }
A complete example:
DisplayItemsList () Widget {
final widget = ListView.builder (
physics: ScrollPhysics (),
reverse: reverse,
shrinkWrap: true,
controller: scrollControllerClientsList,
itemCount:items.length,
itemBuilder: (_, index) {
log ('displayItemsList: itemBuilder: index: $ index');
if (index> = items.length) {
return const Offstage ();
}
return displayOneOiLine (index);
},
);

Container has its size restrained when using with BottomNavigationBar

I have a screen that is applied with BottomNavigationBar. With the index = 0, it will lead to home.dart.
Inside home.dart, I want to have to a column of Widgets. It contains 2 titles(put in Row widgets) and 2 listViews. The 1st ListView I want it to scroll horizontally, and the 2nd one vertical. Both ListView is scrollable. However, it seems that both lists(or containers) are restrained in size somehow, because the 2nd ListView scroll behavior is that it only scroll inside the bottom half of the screen, not the whole screen.
I thought of adding a SingleChildScrollView with Expanded outside the whole Container in home.dart. But it return the error
mainScreen.dart
int _currentTab = 0;
void onTabTapped(int tabNumber) {
setState(() {
_currentTab = tabNumber;
});
}
#override
void initState() {
super.initState();
this.setState(() {
contents = [
HomeTab(),
DownloadedTab(),
SettingTab()
];
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Container(
child: contents != null ? contents[_currentTab] : Text("Page is loaded"),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
onTap: onTabTapped,
backgroundColor: Theme.ColorsMode.appBarGradientStart,
currentIndex: _currentTab,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Home')),
BottomNavigationBarItem(
icon: new Icon(Icons.file_download),
title: new Text('Download')),
BottomNavigationBarItem(
icon: new Icon(Icons.settings),
title: new Text('Setting')),
],
),
),
);
}
home.dart
#override
Widget build(Build context) {
return Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text('Course', textAlign: TextAlign.left, style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
],
),
Expanded(
child: Container(
// height: 6000.0,
child: ListView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: (showInHomeClass != null && showInHomeClass != null) ? showInHomeClass.length : 0,
itemBuilder: (context, index) {
return Container(
width: MediaQuery.of(context).size.width * 0.6,
child: FittedBox(
fit: BoxFit.cover,
child: GestureDetector(
onTap: () {},
child: Card(
child: Center (
child: Image.network('https://example.com'),
),
),
),
),
);
}
),
),
),
Row(
children: <Widget>[
Text('News', textAlign: TextAlign.left, style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
],
),
Expanded(
child: Container(
// height: 6000.0,
child: ListView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
itemCount: (showInHomeClass != null && showInHomeClass != null) ? showInHomeClass.length : 0,
itemBuilder: (context, index) {
return Container(
width: MediaQuery.of(context).size.width * 0.6,
child: FittedBox(
fit: BoxFit.cover,
child: GestureDetector(
onTap: () {},
child: Card(
child: Center (
child: Image.network('https://example.com'),
),
),
),
),
);
}
),
),
)
],
),
);
}
error when adding SingleChildScrollView and Expanded
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building Listener:
'package:flutter/src/widgets/framework.dart': Failed assertion: line 1786 pos 12: '_elements.contains(element)': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=BUG.md
The relevant error-causing widget was
SingleChildScrollView
lib\…\Home\Home.dart:115
#4 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3176
#5 Element.updateChild
package:flutter/…/widgets/framework.dart:2988
#6 SingleChildRenderObjectElement.mount
package:flutter/…/widgets/framework.dart:5445
...
════════════════════════════════════════════════════════════════════════════════
Reloaded 6 of 675 libraries in 919ms.
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 1786 pos 12: '_elements.contains(element)': is not true.
The relevant error-causing widget was
SingleChildScrollView
Any suggestions?

Categories

Resources