'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: - flutter
I try to generate a list of items out of a database (sqflite). Everything seems to work fine until my database has 3 items.
When I go to the AddBodyStatsScreen and back to the BodyStatsListScreen the program crashes. When I start debugging on AVD and I have already 3 items in the database I get the following errors:
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building MediaQuery(MediaQueryData(size: Size(480.0, 1042.7), devicePixelRatio: 3.0, textScaleFactor: 1.0, platformBrightness: Brightness.light, padding: EdgeInsets.zero, viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, alwaysUse24HourFormat: false, accessibleNavigation: false, highContrast: false, disableAnimations: false, invertColors: false, boldText: false, navigationMode: traditional, gestureSettings: DeviceGestureSettings(touchSlop: 8.0), displayFeatures: [])):
'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 261 pos 16: 'child == null || indexOf(child) > index': 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
ListView
When the exception was thrown, this was the stack
#2 RenderSliverMultiBoxAdaptor._debugVerifyChildOrder
#3 RenderSliverMultiBoxAdaptor.debugChildIntegrityEnabled=.<anonymous closure>
#4 RenderSliverMultiBoxAdaptor.debugChildIntegrityEnabled=
#5 SliverMultiBoxAdaptorElement.performRebuild
#6 SliverMultiBoxAdaptorElement.update
#7 Element.updateChild
#8 ComponentElement.performRebuild
#9 Element.rebuild
#10 ProxyElement.update
#11 Element.updateChild
#12 SingleChildRenderObjectElement.update
#13 Element.updateChild
#14 RenderObjectElement.updateChildren
#15 MultiChildRenderObjectElement.update
#16 Element.updateChild
#17 SingleChildRenderObjectElement.update
#18 Element.updateChild
#19 SingleChildRenderObjectElement.update
#20 Element.updateChild
#21 SingleChildRenderObjectElement.update
#22 Element.updateChild
#23 SingleChildRenderObjectElement.update
#24 Element.updateChild
#25 ComponentElement.performRebuild
#26 StatefulElement.performRebuild
#27 Element.rebuild
#28 StatefulElement.update
#29 Element.updateChild
#30 SingleChildRenderObjectElement.update
#31 Element.updateChild
#32 ComponentElement.performRebuild
#33 Element.rebuild
#34 ProxyElement.update
#35 Element.updateChild
#36 SingleChildRenderObjectElement.update
#37 Element.updateChild
#38 ComponentElement.performRebuild
#39 Element.rebuild
#40 ProxyElement.update
#41 Element.updateChild
#42 SingleChildRenderObjectElement.update
#43 Element.updateChild
#44 SingleChildRenderObjectElement.update
#45 Element.updateChild
#46 SingleChildRenderObjectElement.update
#47 Element.updateChild
#48 ComponentElement.performRebuild
#49 Element.rebuild
#50 ProxyElement.update
#51 Element.updateChild
#52 ComponentElement.performRebuild
#53 StatefulElement.performRebuild
#54 Element.rebuild
#55 StatefulElement.update
#56 Element.updateChild
#57 ComponentElement.performRebuild
#58 StatefulElement.performRebuild
#59 Element.rebuild
#60 StatefulElement.update
#61 Element.updateChild
#62 ComponentElement.performRebuild
#63 Element.rebuild
#64 ProxyElement.update
#65 Element.updateChild
#66 ComponentElement.performRebuild
#67 Element.rebuild
#68 StatelessElement.update
#69 Element.updateChild
#70 ComponentElement.performRebuild
#71 StatefulElement.performRebuild
#72 Element.rebuild
#73 BuildOwner.buildScope
#74 WidgetsBinding.drawFrame
#75 RendererBinding._handlePersistentFrameCallback
#76 SchedulerBinding._invokeFrameCallback
#77 SchedulerBinding.handleDrawFrame
#78 SchedulerBinding._handleDrawFrame
#79 _invoke (dart:ui/hooks.dart:145:13)
#80 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:338:5)
#81 _drawFrame (dart:ui/hooks.dart:112:31)
(elided 2 frames from class _AssertionError)
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
A RenderSliverPadding expected a child of type RenderSliver but received a child of type RenderErrorBox.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
FutureBuilder<List<BodyStats>>
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4692 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
FutureBuilder<List<BodyStats>>
════════════════════════════════════════════════════════════════════════════════
Restarted application in 2.102ms.
════════ Exception caught by rendering library ═════════════════════════════════
'package:flutter/src/material/material.dart': Failed assertion: line 735 pos 12: 'referenceBox.attached': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
Here is the code:
import 'package:gym_app/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:gym_app/models/body_stats.dart';
class BodyStatsListScreen extends StatefulWidget {
const BodyStatsListScreen({super.key});
#override
_BodyStatsListScreenState createState() => _BodyStatsListScreenState();
}
class _BodyStatsListScreenState extends State<BodyStatsListScreen> {
// void _showSnackBar(BuildContext context, String text) {
// ScaffoldMessenger.of(context)
// ..hideCurrentSnackBar()
// ..showSnackBar(SnackBar(content: Text(text)));
// }
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Meine Body Stats'),
),
body: Center(
child: FutureBuilder<List<BodyStats>>(
future: DatabaseHelper.instance.getBodyStats('bodyStats'),
builder: (BuildContext context, AsyncSnapshot<List<BodyStats>> snapshot) {
if (!snapshot.hasData) {
return const Center(child: Text('Lade Daten...'));
}
return snapshot.data!.isEmpty
? const Center(
child: Text('Keine Daten vorhanden.'),
)
: ListView(
children: snapshot.data!.map((item) {
return Slidable(
// Specify a key if the Slidable is dismissible.
key: const ValueKey(0),
// The end action pane is the one at the right or the bottom side.
endActionPane: ActionPane(
motion: const ScrollMotion(),
children: [
SlidableAction(
onPressed: (context) {
Future.delayed(Duration.zero, () {
Navigator.pushNamed(context, '/addBodyStats', arguments: item).then((value) => setState(() {}));
});
},
backgroundColor: const Color.fromARGB(255, 112, 112, 112),
foregroundColor: Colors.white,
icon: Icons.edit,
label: 'editieren',
),
SlidableAction(
onPressed: (context) {
setState(() {
DatabaseHelper.instance.remove('bodyStats', item.datum!);
});
// _showSnackBar(context, '${item.datum} gelöscht');
},
backgroundColor: const Color(0xFFFE4A49),
foregroundColor: Colors.white,
icon: Icons.delete,
label: 'löschen',
),
],
),
// The child of the Slidable is what the user sees when the
// component is not dragged.
child: ListTile(title: Text(item.datum.toString())),
);
}).toList(),
);
}),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Future.delayed(Duration.zero, () {
Navigator.pushNamed(context, '/addBodyStats', arguments: BodyStats(datum: '')).then((value) => setState(() {}));
});
},
child: const Icon(Icons.add),
),
);
}
}
And the related widget to create an item:
import 'package:flutter/material.dart';
import 'package:gym_app/models/body_stats.dart';
import 'package:intl/intl.dart';
import 'package:gym_app/database_helper.dart';
class AddBodyStatsScreen extends StatefulWidget {
const AddBodyStatsScreen({super.key});
#override
State<AddBodyStatsScreen> createState() => _AddBodyStatsScreenState();
}
class _AddBodyStatsScreenState extends State<AddBodyStatsScreen> {
bool taped = false;
DateTime selectedDate = DateTime.now();
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(context: context, initialDate: selectedDate, firstDate: DateTime(2015, 8), lastDate: DateTime.now());
if (picked != null && picked != selectedDate) {
setState(() {
selectedDate = picked;
});
}
}
// void _showSnackBar(BuildContext context, String text) {
// ScaffoldMessenger.of(context)
// ..hideCurrentSnackBar()
// ..showSnackBar(SnackBar(content: Text(text)));
// }
#override
Widget build(BuildContext context) {
final editedBodyStats = ModalRoute.of(context)!.settings.arguments as BodyStats;
bool inEditMode = editedBodyStats.datum != '';
if (inEditMode && taped == false) {
selectedDate = DateFormat('dd.MM.yyyy').parse(editedBodyStats.datum!);
} else {}
return Scaffold(
appBar: AppBar(
title: Text(inEditMode ? 'Body Stats editieren' : 'Body Stats hinzufügen'),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
InkWell(
child: Text(DateFormat('dd.MM.yyyy').format(selectedDate)),
onTap: () {
taped = true;
_selectDate(context);
},
)
],
),
),
ElevatedButton(
onPressed: () async {
if (inEditMode) {
await DatabaseHelper.instance.update('bodyStats', BodyStats(datum: DateFormat('dd.MM.yyyy').format(selectedDate)));
// _showSnackBar(context, '${DateFormat('dd.MM.yyyy').format(selectedDate)} wurde editiert');
} else {
if (await DatabaseHelper.instance.uidExists('bodyStats', DateFormat('dd.MM.yyyy').format(selectedDate))) {
await DatabaseHelper.instance.update('bodyStats', BodyStats(datum: DateFormat('dd.MM.yyyy').format(selectedDate)));
// _showSnackBar(context, '${DateFormat('dd.MM.yyyy').format(selectedDate)} wurde editiert');
} else {
await DatabaseHelper.instance.add('bodyStats', BodyStats(datum: DateFormat('dd.MM.yyyy').format(selectedDate)));
}
}
Future.delayed(Duration.zero, () {
Navigator.pop(context);
});
},
child: Text(inEditMode ? 'editieren' : 'hinzufügen'),
)
],
),
);
}
}
import 'dart:io';
import 'package:gym_app/models/body_stats.dart';
// ignore: depend_on_referenced_packages
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper {
//SingeltonPattern
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirecory = await getApplicationDocumentsDirectory();
String path = join(documentsDirecory.path, 'gym_app.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE bodyStats(
datum TEXT PRIMARY KEY,
gewicht TEXT,
koerperfett TEXT,
muskelanteil TEXT,
halsumfang TEXT,
schulterumfang TEXT,
brustumfang TEXT,
armumfangRe TEXT,
armumfangLi TEXT,
oberschenkelumfangRe TEXT,
oberschenkelumfangLi TEXT,
bauchumfang TEXT,
hueftumfang TEXT,
wadenumfangRe TEXT,
wadenumfangLi TEXT
)
''');
}
Future<List<BodyStats>> getBodyStats(String dbTable) async {
Database db = await instance.database;
var bodyStats = await db.query(dbTable, orderBy: 'datum');
List<BodyStats> bodyStatsList = bodyStats.isNotEmpty ? bodyStats.map((e) => BodyStats.fromMap(e)).toList() : [];
return bodyStatsList;
}
Future<int> add(String dbTable, BodyStats item) async {
Database db = await instance.database;
return await db.insert(dbTable, item.toMap());
}
Future<int> remove(String dbTable, String datum) async {
Database db = await instance.database;
return await db.delete(dbTable, where: 'datum = ?', whereArgs: [datum]);
}
Future<int> update(String dbTable, BodyStats item) async {
Database db = await instance.database;
return await db.update(dbTable, item.toMap(), where: 'datum = ?', whereArgs: [item.datum]);
}
Future<bool> uidExists(String dbTable, String datum) async {
var result = await _database!.rawQuery(
'SELECT EXISTS(SELECT 1 FROM $dbTable WHERE datum= "$datum")',
);
int exists = Sqflite.firstIntValue(result)!;
return exists == 1;
}
}
import 'dart:convert';
class BodyStats {
final String? datum;
final String? gewicht;
final String? koerperfett;
final String? muskelanteil;
final String? halsumfang;
final String? schulterumfang;
final String? brustumfang;
final String? armumfangRe;
final String? armumfangLi;
final String? oberschenkelumfangRe;
final String? oberschenkelumfangLi;
final String? bauchumfang;
final String? hueftumfang;
final String? wadenumfangRe;
final String? wadenumfangLi;
BodyStats(
{this.datum,
this.gewicht,
this.koerperfett,
this.muskelanteil,
this.halsumfang,
this.schulterumfang,
this.brustumfang,
this.armumfangRe,
this.armumfangLi,
this.oberschenkelumfangRe,
this.oberschenkelumfangLi,
this.bauchumfang,
this.hueftumfang,
this.wadenumfangRe,
this.wadenumfangLi});
BodyStats copyWith(
{String? datum,
String? gewicht,
String? koerperfett,
String? muskelanteil,
String? halsumfang,
String? schulterumfang,
String? brustumfang,
String? armumfangRe,
String? armumfangLi,
String? oberschenkelumfangRe,
String? oberschenkelumfangLi,
String? bauchumfang,
String? hueftumfang,
String? wadenumfangRe,
String? wadenumfangLi}) {
return BodyStats(
datum: datum ?? this.datum,
gewicht: gewicht ?? this.gewicht,
koerperfett: koerperfett ?? this.koerperfett,
muskelanteil: muskelanteil ?? this.muskelanteil,
halsumfang: halsumfang ?? this.halsumfang,
schulterumfang: schulterumfang ?? this.schulterumfang,
brustumfang: brustumfang ?? this.brustumfang,
armumfangRe: armumfangRe ?? this.armumfangRe,
armumfangLi: armumfangLi ?? this.armumfangLi,
oberschenkelumfangRe: oberschenkelumfangRe ?? this.oberschenkelumfangRe,
oberschenkelumfangLi: oberschenkelumfangLi ?? this.oberschenkelumfangLi,
bauchumfang: bauchumfang ?? this.bauchumfang,
hueftumfang: hueftumfang ?? this.hueftumfang,
wadenumfangRe: wadenumfangRe ?? this.wadenumfangRe,
wadenumfangLi: wadenumfangLi ?? this.wadenumfangLi);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'datum': datum,
'gewicht': gewicht,
'koerperfett': koerperfett,
'muskelanteil': muskelanteil,
'halsumfang': halsumfang,
'schulterumfang': schulterumfang,
'brustumfang': brustumfang,
'armumfangRe': armumfangRe,
'armumfangLi': armumfangLi,
'oberschenkelumfangRe': oberschenkelumfangRe,
'oberschenkelumfangLi': oberschenkelumfangLi,
'bauchumfang': bauchumfang,
'hueftumfang': hueftumfang,
'wadenumfangRe': wadenumfangRe,
'wadenumfangLi': wadenumfangLi
};
}
factory BodyStats.fromMap(Map<String, dynamic> map) {
return BodyStats(
datum: map['datum'] != null ? map['datum'] as String : null,
gewicht: map['gewicht'] != null ? map['gewicht'] as String : null,
koerperfett: map['koerperfett'] != null ? map['koerperfett'] as String : null,
muskelanteil: map['muskelanteil'] != null ? map['muskelanteil'] as String : null,
halsumfang: map['halsumfang'] != null ? map['halsumfang'] as String : null,
schulterumfang: map['schulterumfang'] != null ? map['schulterumfang'] as String : null,
brustumfang: map['brustumfang'] != null ? map['brustumfang'] as String : null,
armumfangRe: map['armumfangRe'] != null ? map['armumfangRe'] as String : null,
armumfangLi: map['armumfangLi'] != null ? map['armumfangLi'] as String : null,
oberschenkelumfangRe: map['oberschenkelumfangRe'] != null ? map['oberschenkelumfangRe'] as String : null,
oberschenkelumfangLi: map['OberschenkelumfangLi'] != null ? map['oberschenkelumfangLi'] as String : null,
bauchumfang: map['bauchumfang'] != null ? map['bauchumfang'] as String : null,
hueftumfang: map['hueftumfang'] != null ? map['hueftumfang'] as String : null,
wadenumfangRe: map['wadenumfangRe'] != null ? map['wadenumfangRe'] as String : null,
wadenumfangLi: map['wadenumfangLi'] != null ? map['wadenumfangLi'] as String : null,
);
}
String toJson() => json.encode(toMap());
factory BodyStats.fromJson(String source) => BodyStats.fromMap(json.decode(source) as Map<String, dynamic>);
#override
String toString() =>
'BodyStats(datum: $datum, gewicht: $gewicht, koerperfett: $koerperfett, muskelanteil: $muskelanteil, halsumfang: $halsumfang, schulterumfang: $schulterumfang, brustumfang: $brustumfang, armumfangRe: $armumfangRe, armumfangLi: $armumfangLi, oberschenkelumfangRe: $oberschenkelumfangRe, oberschenkelumfangLi: $oberschenkelumfangLi, bauchumfang: $bauchumfang, hueftumfang: $hueftumfang, wadenumfangRe: $wadenumfangRe, wadenumfangLi: $wadenumfangLi)';
#override
bool operator ==(covariant BodyStats other) {
if (identical(this, other)) return true;
return other.datum == datum &&
other.gewicht == gewicht &&
other.koerperfett == koerperfett &&
other.muskelanteil == muskelanteil &&
other.halsumfang == halsumfang &&
other.schulterumfang == schulterumfang &&
other.brustumfang == brustumfang &&
other.armumfangRe == armumfangRe &&
other.armumfangLi == armumfangLi &&
other.oberschenkelumfangRe == oberschenkelumfangRe &&
other.oberschenkelumfangLi == oberschenkelumfangLi &&
other.bauchumfang == bauchumfang &&
other.hueftumfang == hueftumfang &&
other.wadenumfangRe == wadenumfangRe &&
other.wadenumfangLi == wadenumfangLi;
}
#override
int get hashCode =>
datum.hashCode ^
gewicht.hashCode ^
koerperfett.hashCode ^
muskelanteil.hashCode ^
halsumfang.hashCode ^
schulterumfang.hashCode ^
brustumfang.hashCode ^
armumfangRe.hashCode ^
armumfangLi.hashCode ^
oberschenkelumfangRe.hashCode ^
oberschenkelumfangLi.hashCode ^
bauchumfang.hashCode ^
hueftumfang.hashCode ^
wadenumfangRe.hashCode ^
wadenumfangLi.hashCode;
}
I have already checked the table of the database but it looks good.
Related
error of no such metheod and jsonDocumentReference
I have a project where I want to update the status of a user to the firebase database and also update the status on Get storage I have written a code that gives me two errors 1. this error Happens when I upload the document to the firebase database it works fine and i can see the changes in database but somehow giving these exception it says : E/flutter ( 2958): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_JsonDocumentReference' E/flutter ( 2958): #0 _JsonStringifier.writeObject (dart:convert/json.dart:794:7) E/flutter ( 2958): #1 _JsonStringifier.writeMap (dart:convert/json.dart:875:7) E/flutter ( 2958): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:830:21) E/flutter ( 2958): #3 _JsonStringifier.writeObject (dart:convert/json.dart:785:9) E/flutter ( 2958): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:983:17) E/flutter ( 2958): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:968:5) E/flutter ( 2958): #6 JsonEncoder.convert (dart:convert/json.dart:345:30) E/flutter ( 2958): #7 JsonCodec.encode (dart:convert/json.dart:231:45) E/flutter ( 2958): #8 StorageImpl.flush (package:get_storage/src/storage/io.dart:34:37) E/flutter ( 2958): #9 GetStorage._flush (package:get_storage/src/storage_impl.dart:144:23) E/flutter ( 2958): #10 GetQueue._check (package:get/get_utils/src/queue/get_queue.dart:42:47) E/flutter ( 2958): #11 GetQueue.add (package:get/get_utils/src/queue/get_queue.dart:29:5) E/flutter ( 2958): #12 GetStorage._addToQueue (package:get_storage/src/storage_impl.dart:139:18) E/flutter ( 2958): #13 Microtask.exec.<anonymous closure> (package:get_storage/src/storage_impl.dart:174:17) E/flutter ( 2958): #14 _microtaskLoop (dart:async/schedule_microtask.dart:40:21) E/flutter ( 2958): #15 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5) E/flutter ( 2958): W/le.helping_han( 2958): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed) [GETX] GOING TO ROUTE /Profile here is my secondd error : 2. the second one I cannot understand the error, after i upload the document to firebase and i go to profile i get this error : after I hot-reload the error is gone ======== Exception caught by widgets library ======================================================= The following NoSuchMethodError was thrown building Profile(dirty): Class '_JsonDocumentReference' has no instance method '[]'. Receiver: Instance of '_JsonDocumentReference' Tried calling: []("status") The relevant error-causing widget was: Profile Profile:file:///D:/FIVERR%20PROJECTS%20FLUTTER/helping_hand/helping_hand/lib/drawers/Slidedrawer.dart:22:20 When the exception was thrown, this was the stack: #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5) #1 Profile.build (package:helping_hand/UI/Other/Profile.dart:65:120) #2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4949:49) #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15) #4 Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5) #5 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5) #6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5) ... Normal element mounting (275 frames) here is my code : BarController.dart (using GetxController) // status Future<void> addStatus(Map<String,String> userStatus) async { loadingbar(); try{ final DocumentReference userstatus= FirebaseFirestore.instance .collection('users') .doc(Auth().currentuser?.email); await userstatus.update({ "status":userStatus['status'],"description":userStatus['description'], }); Userbox.write('userStatus', userstatus); }catch(e){ if (kDebugMode) { print('add status error ::: $e'); } Get.snackbar('error','we have encountered an error'); } loadingbaroff(); } bool isloading = false; void loadingbar() { isloading = true; update(); } void loadingbaroff() { isloading = false; update(); } Mystatus.dart : Container( width: MediaQuery.of(context).size.width-50, margin: const EdgeInsets.only(top: 16,bottom: 24,left: 8,right: 8), child: ElevatedButton( style: const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent) ), onPressed: () async { if(selectpartycontroller.text.isNotEmpty&&description.text.isNotEmpty){ Map<String,String> userstatus = ({"status":selectpartycontroller.text.toString(), "description":description.text.toString(),}); await barController.addStatus(userstatus); selectpartycontroller.clear(); description.clear(); if (kDebugMode) { print(Userbox.read(Userbox.read('userdata')['country_code'])); } }else{ Get.snackbar('fill details', 'select an option and add a description'); } }, child:const Text('Continue',style: TextStyle(color: Colors.white),))), profile.dart : Container( alignment: Alignment.centerLeft, padding: const EdgeInsets.only(top: 24,bottom: 12,left: 24,right: 12), child: Text('User status : ${Userbox.read('userStatus') == null? 'not fetched':Userbox.read('userStatus')['status']}', style: const TextStyle(color: Colors.redAccent,fontWeight: FontWeight.normal,fontSize: 16),),), Container( alignment: Alignment.centerLeft, padding: const EdgeInsets.only(top: 24,bottom: 12,left: 24,right: 12), child: Text('status description : ${Userbox.read('userStatus')== null?'not fetched':Userbox.read('userStatus')['description']}', style: const TextStyle(color: Colors.redAccent,fontWeight: FontWeight.normal,fontSize: 16),),),
for the first error, check the directory with the issue and see how you can fix that. Profile Profile:file:///D:/FIVERR%20PROJECTS%20FLUTTER/helping_hand/helping_hand/lib/drawers/Slidedrawer.dart:22:20 The reason you're getting the second error is that the key "status" was null so to handle that, add a null check, // status Future<void> addStatus(Map<String, String> userStatus) async { loadingbar(); try { final DocumentReference userstatus = FirebaseFirestore.instance .collection('users') .doc(Auth().currentuser?.email); await userstatus.update({ if (userStatus['status'] != null) "status": userStatus['status'], if (userStatus['description'] != null) "description": userStatus['description'], }); Userbox.write('userStatus', userstatus); } catch (e) { if (kDebugMode) { print('add status error ::: $e'); } Get.snackbar('error', 'we have encountered an error'); } loadingbaroff(); } bool isloading = false; void loadingbar() { isloading = true; update(); } void loadingbaroff() { isloading = false; update(); } On the userstatus, you'll want to remove the "toString()" method and clear Controllers after the entire Operations Container( width: MediaQuery.of(context).size.width-50, margin: const EdgeInsets.only(top: 16,bottom: 24,left: 8,right: 8), child: ElevatedButton( style: const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent) ), onPressed: () async { if(selectpartycontroller.text.isNotEmpty&&description.text.isNotEmpty){ Map<String,String> userstatus = ({"status":selectpartycontroller, "description":description.text,}); await barController.addStatus(userstatus); if (kDebugMode) { print(Userbox.read(Userbox.read('userdata')['country_code'])); } }else{ Get.snackbar('fill details', 'select an option and add a description'); } selectpartycontroller.clear(); description.clear();}, child:const Text('Continue',style: TextStyle(color: Colors.white),))),
dart/flutter:: type 'Null' is not a subtype of type 'String' in type cast ERRor, not able to fetch data
I am running into a "type 'Null' is not a subtype of type 'String' in type cast" when I try to retrieve the data. not sure what the issue is... I think the data is not being found or something along those lines source code:: https://github.com/casas1010/flutter_firebase_vendor_management error message:: ════════ Exception caught by widgets library ═══════════════════════════════════ The following _CastError was thrown building JobApplicationsListView(dirty): type 'Null' is not a subtype of type 'String' in type cast The relevant error-causing widget was JobApplicationsListView lib/…/job_applications/job_application_view.dart:75 When the exception was thrown, this was the stack #0 new CloudJobApplication.fromSnapshot package:ijob_clone_app/…/cloud/cloud_job_application.dart:27 #1 FirebaseCloudStorage.allJobApplications.<anonymous closure>.<anonymous closure> package:ijob_clone_app/…/cloud/firebase_cloud_storage.dart:49 #2 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31) #3 ListIterator.moveNext (dart:_internal/iterable.dart:342:26) #4 WhereIterator.moveNext (dart:_internal/iterable.dart:438:22) #5 Iterable.length (dart:core/iterable.dart:497:15) #6 JobApplicationsListView.build package:ijob_clone_app/…/widgets/job_application_list_widget.dart:27 #7 StatelessElement.build package:flutter/…/widgets/framework.dart:4949 #8 ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:4878 #9 Element.rebuild package:flutter/…/widgets/framework.dart:4604 #10 ComponentElement._firstBuild package:flutter/…/widgets/framework.dart:4859 #11 ComponentElement.mount package:flutter/…/widgets/framework.dart:4853 #12 Element.inflateWidget package:flutter/…/widgets/framework.dart:3863 #13 Element.updateChild package:flutter/…/widgets/framework.dart:3586 #14 ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:4904 #15 StatefulElement.performRebuild package:flutter/…/widgets/framework.dart:5050 #16 Element.rebuild package:flutter/…/widgets/framework.dart:4604 #17 BuildOwner.buildScope package:flutter/…/widgets/framework.dart:2667 #18 WidgetsBinding.drawFrame package:flutter/…/widgets/binding.dart:882 #19 RendererBinding._handlePersistentFrameCallback package:flutter/…/rendering/binding.dart:378 #20 SchedulerBinding._invokeFrameCallback package:flutter/…/scheduler/binding.dart:1175 #21 SchedulerBinding.handleDrawFrame package:flutter/…/scheduler/binding.dart:1104 #22 SchedulerBinding._handleDrawFrame package:flutter/…/scheduler/binding.dart:1015 #23 _invoke (dart:ui/hooks.dart:148:13) #24 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:318:5) #25 _drawFrame (dart:ui/hooks.dart:115:31) ════════════════════════════════════════════════════════════════════════════════ D/TrafficStats( 9769): tagSocket(99) with statsTag=0xffffffff, statsUid=-1 CloudJobApplication:: #immutable class CloudJobApplication { final String documentId; final String jobApplicatorId; final String jobApplicationState; final String jobApplicationSubState; const CloudJobApplication({ required this.documentId, required this.jobApplicatorId, required this.jobApplicationState, required this.jobApplicationSubState, }); // acts as constructor CloudJobApplication.fromSnapshot( QueryDocumentSnapshot<Map<String, dynamic>> snapshot) : documentId = snapshot.id, jobApplicatorId = snapshot.data()[jobApplicatorIdColumn] as String, jobApplicationState = snapshot.data()[jobApplicationStateColumn] as String, jobApplicationSubState = snapshot.data()[jobApplicationSubStateColumn] as String; } FirebaseCloudStorage:: class FirebaseCloudStorage { final job = FirebaseFirestore.instance.collection('jobs'); final jobApplication = FirebaseFirestore.instance.collection('job applications'); // This works perfect for getting the jobs Stream<Iterable<CloudJob>> allJobs({required String jobCreatorId}) => job.snapshots().map((event) => event.docs .map((doc) => CloudJob.fromSnapshot(doc)) .where((job) => job.jobCreatorId == jobCreatorId)); // this does not work. i copied the code from above and changed it Stream<Iterable<CloudJobApplication>> allJobApplications() => jobApplication.snapshots().map((event) => event.docs .map((doc) => CloudJobApplication.fromSnapshot(doc)) .where((jobApplication) => jobApplication.documentId == 'f2FvzZmr51v1wyrYZYoM')); // singleton static final FirebaseCloudStorage _shared = FirebaseCloudStorage._sharedInstance(); FirebaseCloudStorage._sharedInstance(); factory FirebaseCloudStorage() => _shared; } JobApplicationsView:: ( this is where the issue starts, the issue appears when this widget tries to retrieve the data from the server i thin ) import 'package:flutter/material.dart'; import '../../services/cloud/cloud_job_application.dart'; import '../../utilities/widgets/job_application_list_widget.dart'; import '../../utilities/widgets/jobs_list_widget.dart'; import '/constants/routes.dart'; import '/enums/menu_action.dart'; import '/services/auth/auth_service.dart'; import '/services/cloud/cloud_job.dart'; import '/services/cloud/firebase_cloud_storage.dart'; import '/utilities/dialogs/logout_dialog.dart'; class JobApplicationsView extends StatefulWidget { const JobApplicationsView({Key? key}) : super(key: key); #override _JobApplicationsViewState createState() => _JobApplicationsViewState(); } class _JobApplicationsViewState extends State<JobApplicationsView> { late final FirebaseCloudStorage _jobsService; String get userId => AuthService.firebase().currentUser!.id; #override void initState() { _jobsService = FirebaseCloudStorage(); super.initState(); } #override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Your job applications'), actions: [ IconButton( onPressed: () { // Navigator.of(context).pushNamed(createOrUpdateJobRoute); }, icon: const Icon(Icons.add), ), PopupMenuButton<MenuAction>( onSelected: (value) async { prin('code removed') }, itemBuilder: (context) { return const [ PopupMenuItem<MenuAction>( value: MenuAction.logout, child: Text('Log out'), ), ]; }, ) ], ), body: StreamBuilder( stream: _jobsService.allJobApplications(), builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.waiting: case ConnectionState.active: if (snapshot.hasData) { final allJobs = snapshot.data as Iterable<CloudJobApplication>; print(snapshot); return JobApplicationsListView( // ERROR IS OCURRING HERE jobs: allJobs, ); return Text('results'); } else { return const CircularProgressIndicator(); } default: return const CircularProgressIndicator(); } }, ), ); } }
Try like this CloudJobApplication.fromSnapshot( QueryDocumentSnapshot<Map<String, dynamic>> snapshot) : documentId = snapshot.id, jobApplicatorId = snapshot.data()[jobApplicatorIdColumn] ?? "", jobApplicationState = snapshot.get(jobApplicationStateColumn) ?? "", jobApplicationSubState = snapshot.get(jobApplicationSubStateColumn) ?? "";
NoSuchMethodError was thrown building Tabs(dirty, state: _TabsState#fefcf): The method '[]' was called on null
I have read similar answers for this type of error but still, I am not able to resolve it in my code. When I tap the button it shows an error screen for some time and then displays loader which should be displayed while the data is being fetched. error screen loading screen final screen here is the code: import 'package:flutter/material.dart'; import 'Dictionary.dart'; import 'Services.dart'; class NewTab extends StatefulWidget { #override _NewTabState createState() => _NewTabState(); } class _NewTabState extends State<NewTab> { List<Dictionary> _users; int len; #override void initState() { super.initState(); Services.getUsers().then((users) { setState(() { _users = users; len = users.length - 1 ; }); }); } #override Widget build(BuildContext context) { Dictionary user = _users[len]; print(user); return FutureBuilder( future: Services.getUsers(), builder: (context,AsyncSnapshot<List<Dictionary>> snapshot){ if(snapshot.data==null){ return Center(child: CircularProgressIndicator()); }else{ return DefaultTabController(length: 2, child:Scaffold( appBar: AppBar( title : Text('Meaning', style: TextStyle( fontFamily: "Pangolin", fontSize: 35, ) ), centerTitle: true, bottom: TabBar( tabs: <Widget>[ Tab(text:'Meaning', icon: Icon(Icons.book_outlined), ), Tab(text:'Example', icon: Icon(Icons.directions_transit) ), ], ), ), body : TabBarView( children: <Widget>[ Container( color: Colors.white, child: Container( color: Colors.black, child: ListView.builder( itemCount: user.meanings.length, itemBuilder: (context, index) { print(index); List<Meaning> mean = user.meanings; return ListTile( title: Text(mean[index].definitions[0].definition , style: TextStyle( color: Colors.white, ), ), ); }, ), ),),Container( child: Text('home'), ),] ) ) ); } }, ); } } code for onpressed function in raised button onPressed: ()=>{ Navigator.of(context).push( new MaterialPageRoute(builder: (BuildContext context) => NewTab()) ) }, code for services.dart import 'package:http/http.dart' as http; import 'Dictionary.dart'; import 'package:dictionary_app/home.dart'; import 'dart:async'; class Services { static final url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/$word'; static Future<List<Dictionary>> getUsers() async { try { print(url); final response = await http.get(Uri.parse(url)); print(response.statusCode); if (200 == response.statusCode) { final List<Dictionary> users = dictionaryFromJson(response.body); return users; } else { return <Dictionary>[]; } } catch (e) { return <Dictionary>[]; } } } error: The following NoSuchMethodError was thrown building NewTab(dirty, state: _NewTabState#1662b): The method '[]' was called on null. Receiver: null Tried calling: [](null) The relevant error-causing widget was: NewTab file:///E:/Flutter-Projects/flutter3/dictionary_app/lib/home.dart:120:74 When the exception was thrown, this was the stack: #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:63:5) #1 _NewTabState.build (package:dictionary_app/newtab.dart:25:30) #2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4749:27) #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4632:15) #4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4805:11) #5 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5) #6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4610:5) #7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4796:11) #8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4605:5) ... Normal element mounting (166 frames) #174 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3662:14) #175 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6285:36) #176 Element.updateChild (package:flutter/src/widgets/framework.dart:3414:18) #177 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5717:32) #178 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6308:17) #179 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #180 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4657:16) #181 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4805:11) #182 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5) #183 StatefulElement.update (package:flutter/src/widgets/framework.dart:4837:5) #184 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #185 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4657:16) #186 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5) #187 ProxyElement.update (package:flutter/src/widgets/framework.dart:4985:5) #188 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #189 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4657:16) #190 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5) #191 ProxyElement.update (package:flutter/src/widgets/framework.dart:4985:5) #192 _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:181:11) #193 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #194 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6154:14) #195 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #196 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4657:16) #197 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4805:11) #198 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5) #199 StatefulElement.update (package:flutter/src/widgets/framework.dart:4837:5) #200 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #201 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6154:14) #202 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #203 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6154:14) #204 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #205 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4657:16) #206 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5) #207 ProxyElement.update (package:flutter/src/widgets/framework.dart:4985:5) #208 Element.updateChild (package:flutter/src/widgets/framework.dart:3401:15) #209 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4657:16) #210 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4805:11) #211 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5) #212 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2619:33) #213 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:878:21) #214 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:328:5) #215 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1147:15) #216 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1084:9) #217 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1000:5) #221 _invoke (dart:ui/hooks.dart:163:10) #222 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:259:5) #223 _drawFrame (dart:ui/hooks.dart:126:31) (elided 3 frames from dart:async)
First of all you can remove your initState method since you are already using the FutureBuilder to fetch your Services.getUsers(). Now, you have defined your variables like this, List<Dictionary> _users; int len; But both of them are null when build method is going to be called for the first time. So inside your build method, you can't directly use, Dictionary user = _users[len]; print(user); Since, _users is null when build is called for the first time. So remove those 2 lines. Now, rest of your code is correct, except for one part, Inside your else case of if(snapshot.data==null), define your user variable like this, else { Dictionary user = snapshot.data!.last; // This gives you the last element of the array Now, your code should work. Here is the paste bin link for the full code of _NewTabState.
You have to initialize your list List<Dictionary> _users = []; It’s better way: snapShot.connectionState == ConnectionState.waiting ? :
Flutter : Save List<dynamic> to SharedPreferences from Json.encode
I want to save AppInfo information from API into SharedPreferences. I have source code and result JSON like this : APP_INFO_API.dart: Future<List> getAppInfo() async { try { final response = await http.get( "${appConfig.baseApiUrl}/${appConfig.appInfoController}/getLogoClient"); final Map<String, dynamic> responseJson = json.decode(response.body); if (responseJson["status"] == "ok") { List appInfoList = responseJson["data"]; print('List Dynamic From API : $appInfoList '); return appInfoList; } else { throw CustomError(responseJson["message"]); } } catch (e) { return Future.error(e.toString()); } } Result JSON List Dynamic From API : [{kodeInfo: 1, namaInfo: Integrasi Operasional Outlet, keteranganInfo: Burger Klenger ERPOS Version 1.2, fileInfo: img-1.png, logoInfo: logo-1.png, loginBackgroundInfo: bfront-1.png, loginLeftInfo: bleft-1.png, loginSupportInfo: bsupport-1.png, createBy: , createTime: 0000-00-00 00:00:00, updateBy: hambaallah, updateTime: 2020-02-09 06:32:57}] I already read the documentation about type data that can be store in SharedPreferences, and I found can be store as List[String]. The problem is return of appInfoList above is List[dynamic], It's possible convert from List[dynamic] to List[String], so i can add it to SharedPreferences ? My Experiment I follow This Link and try to implement it. I create GlobalProvider To Store Value From API. class GlobalProvider extends ChangeNotifier { static const _APP_INFO_LIST123 = "appInfoList123"; GlobalProvider() { syncDataWithProvider(); } List<AppInfoModel> appInfoList123 = []; Future updateSharedPreferencesAppInfo123(List<dynamic> value) async { List<String> myAppInfoList123 = value.map((e) => json.encode(e)).toList(); SharedPreferences prefs = await SharedPreferences.getInstance(); final result = await prefs.setStringList(_APP_INFO_LIST123, myAppInfoList123); print('result from updateSP $result'); print('Myappinfolist123 : $myAppInfoList123'); } Future syncDataWithProvider() async { SharedPreferences prefs = await SharedPreferences.getInstance(); var result = prefs.getStringList(_APP_INFO_LIST123); print('The Result is $result'); if (result != null) { appInfoList123 = result .map<AppInfoModel>((e) => AppInfoModel.fromJson(json.decode(e))) .toList(); } print('Hore $appInfoList123'); notifyListeners(); } } Then, when I access it like this : SplashScreen.dart class _SplashScreenState extends State<SplashScreen> { GlobalProvider globalProvider; #override void didChangeDependencies() { super.didChangeDependencies(); globalProvider = Provider.of<GlobalProvider>(context); testing(globalProvider); } testing(GlobalProvider gp) async { final appInfoList = appInfoApi.getAppInfo(); final result = await appInfoList; print('Hello List Dynamic From didChangeDependecies : $result'); return await gp.updateSharedPreferencesAppInfo123(result); } #override Widget build(BuildContext context) { return Scaffold( body: Center(child: Text(globalProvider.appInfoList123[0].fileInfo)), <!!! IN HERE ); } } But i got this error Error I/flutter (26131): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter (26131): The following RangeError was thrown building SplashScreen(dirty, dependencies: I/flutter (26131): [_DefaultInheritedProviderScope<GlobalProvider>], state: _SplashScreenState#a10e3): I/flutter (26131): RangeError (index): Invalid value: Valid value range is empty: 0 I/flutter (26131): I/flutter (26131): The relevant error-causing widget was: I/flutter (26131): SplashScreen lib\main.dart:42 I/flutter (26131): I/flutter (26131): When the exception was thrown, this was the stack: I/flutter (26131): #0 List.[] (dart:core-patch/growable_array.dart:146:60) I/flutter (26131): #1 _SplashScreenState.build package:klenger_burger_app/screens/splash_screen.dart:88 I/flutter (26131): #2 StatefulElement.build package:flutter/…/widgets/framework.dart:4590 I/flutter (26131): #3 ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:4478 I/flutter (26131): #4 StatefulElement.performRebuild package:flutter/…/widgets/framework.dart:4646 I/flutter (26131): #5 Element.rebuild package:flutter/…/widgets/framework.dart:4202 I/flutter (26131): #6 ComponentElement._firstBuild package:flutter/…/widgets/framework.dart:4461 I/flutter (26131): #7 StatefulElement._firstBuild package:flutter/…/widgets/framework.dart:4637 I/flutter (26131): #8 ComponentElement.mount package:flutter/…/widgets/framework.dart:4456 I/flutter (26131): ... Normal element mounting (115 frames) I/flutter (26131): #123 Element.inflateWidget package:flutter/…/widgets/framework.dart:3430 I/flutter (26131): #124 MultiChildRenderObjectElement.mount package:flutter/…/widgets/framework.dart:5857 I/flutter (26131): ... Normal element mounting (253 frames) I/flutter (26131): #377 Element.inflateWidget package:flutter/…/widgets/framework.dart:3430 I/flutter (26131): #378 Element.updateChild package:flutter/…/widgets/framework.dart:3198 I/flutter (26131): #379 ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:4498 I/flutter (26131): #380 _InheritedProviderScopeMixin.performRebuild package:provider/src/inherited_provider.dart:220 I/flutter (26131): #381 Element.rebuild package:flutter/…/widgets/framework.dart:4202 I/flutter (26131): #382 ComponentElement._firstBuild package:flutter/…/widgets/framework.dart:4461 I/flutter (26131): #383 ComponentElement.mount package:flutter/…/widgets/framework.dart:4456 I/flutter (26131): ... Normal element mounting (7 frames) I/flutter (26131): #390 SingleChildWidgetElementMixin.mount package:nested/nested.dart:223 I/flutter (26131): ... Normal element mounting (7 frames) I/flutter (26131): #397 _NestedHookElement.mount package:nested/nested.dart:188 I/flutter (26131): ... Normal element mounting (7 frames) I/flutter (26131): #404 SingleChildWidgetElementMixin.mount package:nested/nested.dart:223 I/flutter (26131): #405 Element.inflateWidget package:flutter/…/widgets/framework.dart:3430 I/flutter (26131): #406 Element.updateChild package:flutter/…/widgets/framework.dart:3198 I/flutter (26131): #407 RenderObjectToWidgetElement._rebuild package:flutter/…/widgets/binding.dart:1142 I/flutter (26131): #408 RenderObjectToWidgetElement.mount package:flutter/…/widgets/binding.dart:1113 I/flutter (26131): #409 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> package:flutter/…/widgets/binding.dart:1055 I/flutter (26131): #410 BuildOwner.buildScope package:flutter/…/widgets/framework.dart:2591 I/flutter (26131): #411 RenderObjectToWidgetAdapter.attachToRenderTree package:flutter/…/widgets/binding.dart:1054 I/flutter (26131): #412 WidgetsBinding.attachRootWidget package:flutter/…/widgets/binding.dart:935 I/flutter (26131): #413 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> package:flutter/…/widgets/binding.dart:917 I/flutter (26131): (elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch) I/flutter (26131): I/flutter (26131): ════════════════════════════════════════════════════════════════════════════════════════════════════ Any recommendation how can i adding List[dynamic] into SharedPreferences ? If you need My Model class AppInfoModel { String kodeInfo; String namaInfo; String keteranganInfo; String fileInfo; String logoInfo; String loginBackgroundInfo; String loginLeftInfo; String loginSupportInfo; String createBy; String createTime; String updateBy; DateTime updateTime; AppInfoModel({ this.kodeInfo, this.namaInfo, this.keteranganInfo, this.fileInfo, this.logoInfo, this.loginBackgroundInfo, this.loginLeftInfo, this.loginSupportInfo, this.createBy, this.createTime, this.updateBy, this.updateTime, }); factory AppInfoModel.fromJson(Map<String, dynamic> json) => AppInfoModel( kodeInfo: json["kodeInfo"] == null ? '' : json["kodeInfo"], namaInfo: json["namaInfo"] == null ? '' : json["namaInfo"], keteranganInfo: json["keteranganInfo"] == null ? '' : json["keteranganInfo"], fileInfo: json["fileInfo"] == null ? '' : json["fileInfo"], logoInfo: json["logoInfo"] == null ? '' : json["logoInfo"], loginBackgroundInfo: json["loginBackgroundInfo"] == null ? '' : json["loginBackgroundInfo"], loginLeftInfo: json["loginLeftInfo"] == null ? '' : json["loginLeftInfo"], loginSupportInfo: json["loginSupportInfo"] == null ? '' : json["loginSupportInfo"], createBy: json["createBy"] == null ? '' : json["createBy"], createTime: json["createTime"] == null ? '' : json["createTime"], updateBy: json["updateBy"] == null ? '' : json["updateBy"], updateTime: DateTime.parse(json["updateTime"]) == null ? '' : DateTime.parse(json["updateTime"]), ); Map toJson() => { 'kodeInfo': this.kodeInfo, 'namaInfo': this.namaInfo, 'keteranganInfo': this.keteranganInfo, 'fileInfo': this.fileInfo, 'logoInfo': this.logoInfo, 'loginBackgroundInfo': this.loginBackgroundInfo, 'loginLeftInfo': this.loginLeftInfo, 'loginSupportInfo': this.loginSupportInfo, 'createBy': this.createBy, 'createTime': this.createTime, 'updateBy': this.updateBy, 'updateTime': this.updateTime, }; } final appInfoModel = AppInfoModel();
You did made a mistake. You need to use FutureBuilder, ValieListenableBuilder or something else to wait while the data is reading. Because syncDataWithProvider is asynchronous call. Which means it will not block current thread while execution is completed. class GlobalProvider extends ChangeNotifier { static const _APP_INFO_LIST123 = "appInfoList123"; GlobalProvider() { future = syncDataWithProvider(); } List<AppInfoModel> appInfoList123 = []; Future future; Fure updateSharedPreferencesAppInfo123(List<dynamic> value) async { List<String> myAppInfoList123 = value.map((e) => json.encode(e)).toList(); SharedPreferences prefs = await SharedPreferences.getInstance(); final result = await prefs.setStringList(_APP_INFO_LIST123, myAppInfoList123); print('result from updateSP $result'); print('Myappinfolist123 : $myAppInfoList123'); } Future syncDataWithProvider() async { SharedPreferences prefs = await SharedPreferences.getInstance(); var result = prefs.getStringList(_APP_INFO_LIST123); print('The Result is $result'); if (result != null) { appInfoList123 = result .map<AppInfoModel>((e) => AppInfoModel.fromJson(json.decode(e))) .toList(); } print('Hore $appInfoList123'); notifyListeners(); } } And your view.dart return FutureBuilder( future: globalProvider.future, builder: (context, snapshot) { if (!snapshot.hasData) { return Text('Loading...'); } return Scaffold( body: Center( child: Text(globalProvider.appInfoList123[0].fileInfo), ), ) } );
How to make a reusable PopupMenuButton in Flutter
I want to make a reusable PopupMenuButton in flutter, so i can call that widget and assign the PopupMenuItem dynamically. Here is what i've done, but it throw a framework error. I am relatively new in flutter. here is class that supposed to be reusable: class PopupMenu { PopupMenu({#required this.title, #required this.onTap}); final String title; final VoidCallback onTap; } class PopupmMenuButtonBuilder { setPopup(List<PopupMenu> popupItem) { return PopupMenuButton<String>( onSelected: (_) { popupItem.forEach((item) => item.onTap); }, itemBuilder: (BuildContext context) { popupItem.forEach( (item) { return <PopupMenuItem<String>>[ PopupMenuItem<String>( value: item.title, child: Text( item.title, ), ), ]; }, ); }, ); } } and then i call the widget like this: child: PopupmMenuButtonBuilder().setPopup([ PopupMenu(title: 'Item 1', onTap: () => print('item 1 selected')), PopupMenu(title: 'Item 2', onTap: () => print('item 2 selected')), ]), It shows the 3 dot icon button, but when i tap the icon it throws this error: I/flutter ( 8509): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ I/flutter ( 8509): The following assertion was thrown while handling a gesture: I/flutter ( 8509): 'package:flutter/src/material/popup_menu.dart': Failed assertion: line 723 pos 10: 'items != null && I/flutter ( 8509): items.isNotEmpty': is not true. I/flutter ( 8509): Either the assertion indicates an error in the framework itself, or we should provide substantially I/flutter ( 8509): more information in this error message to help you determine and fix the underlying cause. I/flutter ( 8509): In either case, please report this assertion by filing a bug on GitHub: I/flutter ( 8509): https://github.com/flutter/flutter/issues/new?template=BUG.md I/flutter ( 8509): When the exception was thrown, this was the stack: I/flutter ( 8509): #2 showMenu (package:flutter/src/material/popup_menu.dart:723:10) I/flutter ( 8509): #3 _PopupMenuButtonState.showButtonMenu (package:flutter/src/material/popup_menu.dart:898:5) I/flutter ( 8509): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14) I/flutter ( 8509): #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30) I/flutter ( 8509): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24) I/flutter ( 8509): #7 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9) I/flutter ( 8509): #8 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:211:7) I/flutter ( 8509): #9 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) I/flutter ( 8509): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:225:20) I/flutter ( 8509): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22) I/flutter ( 8509): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) I/flutter ( 8509): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)I/flutter ( 8509): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)I/flutter ( 8509): #18 _invoke1 (dart:ui/hooks.dart:233:10) I/flutter ( 8509): #19 _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5) I/flutter ( 8509): (elided 5 frames from class _AssertionError and package dart:async) I/flutter ( 8509): Handler: onTap I/flutter ( 8509): Recognizer: I/flutter ( 8509): TapGestureRecognizer#8968f(debugOwner: GestureDetector, state: ready, won arena, finalPosition: I/flutter ( 8509): Offset(339.0, 54.0), sent tap down) I/flutter ( 8509): ════════════════════════════════════════════════════════════════════════════════════════════════════
Your itemBuilder needs to return a List. It doesn't actually return anything - note how the return is inside the forEach so it's just returning from the lambda. In general, forEach should sometimes be avoided. Also, the PopupMenuButtonBuilder class is redundant - it could be replaced with a static or top-level function. One other thing that's unclear is why you want to call each onTap for every select. As you currently have it it's going to call every callback! Try this: class PopupMenu { PopupMenu({#required this.title, #required this.onTap}); final String title; final VoidCallback onTap; static PopupMenuButton<String> createPopup(List<PopupMenu> popupItems) { return PopupMenuButton<String>( onSelected: (value) { popupItems.firstWhere((e) => e.title == value).onTap(); }, itemBuilder: (context) => popupItems .map((item) => PopupMenuItem<String>( value: item.title, child: Text( item.title, ), )) .toList(), ); } }
You can also create a changeable list to append to the Popup menu instead of manually creating it one by one in the child child: PopupMenu(popUpList: _popUpList).createPopup()), then in the Popup menu class class PopupMenu { const PopupMenu({this.popUpList}); final List<PopUpList> popUpList; PopupMenuButton<String> createPopup() { return PopupMenuButton<String>( onSelected: (value) { popUpList.firstWhere((e) => e.title == value).onTap(); }, itemBuilder: (context) => popUpList .map((item) => PopupMenuItem<String>( value: item.title, child: Text(item.title), )).toList(), ); } } model class PopUpList{ String title; VoidCallback onTap; PopUpList({this.onTap, this.title}); } cheers!