VideoPlayerController.network() ran into source error - flutter

Im trying to play a video from the internet using VideoPlayerController.network() method but every single url that i try face with an error which is specified below :
Source error.
E/flutter ( 4250): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(VideoError, Video player had error com.google.android.exoplayer2.ExoPlaybackException: com.google.android.exoplayer2.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_480_1_5MG.mp4, null)
E/flutter ( 4250): #0 ChewieController._initialize (package:chewie/src/chewie_player.dart:291:7)
E/flutter ( 4250): <asynchronous suspension>
E/flutter ( 4250): #1 new ChewieController (package:chewie/src/chewie_player.dart:197:5)
E/flutter ( 4250): #2 _ChewieListState.initState (package:flutterappvideoandshit/screens/chewie_list.dart:20:25)
E/flutter ( 4250): #3 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4640:58)
E/flutter ( 4250): #4 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter ( 4250): #5 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter ( 4250): #6 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter ( 4250): #7 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5830:14)
E/flutter ( 4250): #8 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter ( 4250): #9 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter ( 4250): #10 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5830:14)
E/flutter ( 4250): #11 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter ( 4250): #12 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter ( 4250): #13 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter ( 4250): #14 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter ( 4250): #15 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
E/flutter ( 4250): #16 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter ( 4250): #17 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter ( 4250): #18 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter ( 4250): #19 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter ( 4250): #20 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter ( 4250): #21 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
E/flutter ( 4250): #22 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter ( 4250): #23 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter ( 4250): #24 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter ( 4250): #25 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter ( 4250): #26 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
E/flutter ( 4250): #27 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter ( 4250): #28 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
E/flutter ( 4250): #29 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)
E/flutter ( 4250): #30 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter ( 4250): #31 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter ( 4250): #32 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter ( 4250): #33 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter ( 4250): #34 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter ( 4250): #35 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
E/flutter ( 4250): #36 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter ( 4250): #37 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter ( 4250): #38 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter ( 4250): #39 SliverMultiBoxAdaptorElement.updateChild (package:flutter/src/widgets/sliver.dart:1147:36)
E/flutter ( 4250): #40 SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1132:20)
E/flutter ( 4250): #41 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2607:19)
and here is my code :
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Video Player"),
),
body: ListView(
children: <Widget>[
ChewieList(
videoPlayerController: VideoPlayerController.asset('assets/videos/soccer.mp4'),
looping: true,
),
ChewieList(
videoPlayerController: VideoPlayerController.network(
'https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'),
),
/*
ChewieList(
videoPlayerController: VideoPlayerController.network(
'http://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'),
)
*/
],
),
);
}
}
class ChewieList extends StatefulWidget {
ChewieList({#required this.videoPlayerController,this.looping,Key key,}) : super(key:key);
final VideoPlayerController videoPlayerController;
final bool looping;
#override
_ChewieListState createState() => _ChewieListState();
}
class _ChewieListState extends State<ChewieList> {
ChewieController _chewieController;
#override
void initState() {
// TODO: implement initState
super.initState();
_chewieController = ChewieController(
videoPlayerController: widget.videoPlayerController,
aspectRatio: 16/9,
autoInitialize: true,
looping: widget.looping,
errorBuilder: (context,errMsg){
return Center(
child:Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.warning,color: Colors.yellowAccent,),
Text("!خطایی در برقراری ارتباط رخ داده است",style: TextStyle(color: Colors.white),)
],
),
);
}
);
}
#override
void dispose() {
// TODO: implement dispose
super.dispose();
widget.videoPlayerController.dispose();
_chewieController.dispose();
}
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(8.0),
child: Chewie(
controller: _chewieController,
),
);
}
}
it's driving me crazy!!!!
guys please help me .

You are using the wrong url. The url you posted is not the real video url but is only a redirect url.
Try with:
VideoPlayerController.network('https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'),
(Remember that iOS simulators and other does not always support video playing.)

Related

Unhandled Exception: Unsupported operation: Cannot add to an unmodifiable list - Flutter

I got this unusual error while making my app. I am not exactly sure what it means to be honest. Also, It only does this error when I click on the checkbox for some reason. If you could please help me figure out what's wrong with the app that would be wonderful. Thank you.
tasks_list.dart
class TasksList extends StatelessWidget {
const TasksList({
Key? key,
required this.tasksList,
}) : super(key: key);
final List tasksList;
#override
Widget build(BuildContext context) {
return ListView.builder(
padding: const EdgeInsets.only(top: 20),
itemCount: tasksList.length,
itemBuilder: (context, index) {
var task = tasksList[index];
return TaskTile(task: task);
},
);
}
}
task_tile.dart
class TaskTile extends StatelessWidget {
const TaskTile({
Key? key,
required this.task,
}) : super(key: key);
final Task task;
#override
Widget build(BuildContext context) {
return Column(
children: [
const SizedBox(width: 4),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Row(
children: [
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(width: 10),
Flexible(
child: Column(
children: [
Text(
task.title,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: const Color(0xFF89ABE3),
fontFamily: 'Source Sans Pro',
fontSize: 19,
decoration: task.isDone!
? TextDecoration.lineThrough
: null,
),
),
const SizedBox(
height: 5,
),
Text(
DateFormat().add_yMMMd().add_Hm().format(
DateTime.parse(task.date),
),
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: 'Source Sans Pro',
fontSize: 15,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.bold,
color: Color(0xFF89ABE3),
),
),
],
),
),
const SizedBox(width: 10),
],
),
),
],
),
),
Row(
children: [
PopupMenu(
favouriteCallback: () => context.read<TasksBloc>().add(
MakeFavouriteTask(task: task),
),
task: task,
),
Transform.scale(
scale: 1.2,
child: Checkbox(
shape: const CircleBorder(
side: BorderSide(
width: 20,
),
),
side: const BorderSide(
color: Color(0xFF89ABE3),
),
activeColor: Colors.greenAccent,
value: task.isDone,
onChanged: task.isDeleted == false
? (value) {
context
.read<TasksBloc>()
.add(UpdateTask(task: task));
}
: null,
),
),
],
),
],
),
const SizedBox(width: 4),
const Divider(
thickness: 2,
),
],
);
}
}
Error Log
E/flutter (19323): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unsupported operation: Cannot add to an unmodifiable list
E/flutter (19323): #0 UnmodifiableListMixin.insert (dart:_internal/list.dart:119:5)
E/flutter (19323): #1 TasksBloc._onUpdateTask (package:todo_list/blocs/tasks_bloc/tasks_bloc.dart:45:24)
E/flutter (19323): #2 Bloc.on.<anonymous closure>.handleEvent (package:bloc/src/bloc.dart:226:26)
E/flutter (19323): #3 Bloc.on.<anonymous closure> (package:bloc/src/bloc.dart:235:9)
E/flutter (19323): #4 _MapStream._handleData (dart:async/stream_pipe.dart:213:31)
E/flutter (19323): #5 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (19323): #6 _rootRunUnary (dart:async/zone.dart:1399:47)
E/flutter (19323): #7 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #8 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #9 CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
E/flutter (19323): #10 _rootRunUnary (dart:async/zone.dart:1399:47)
E/flutter (19323): #11 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #12 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #13 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (19323): #14 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (19323): #15 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (19323): #16 _WhereStream._handleData (dart:async/stream_pipe.dart:195:12)
E/flutter (19323): #17 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (19323): #18 _rootRunUnary (dart:async/zone.dart:1407:13)
E/flutter (19323): #19 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #20 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #21 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (19323): #22 _DelayedData.perform (dart:async/stream_impl.dart:515:14)
E/flutter (19323): #23 _PendingEvents.handleNext (dart:async/stream_impl.dart:620:11)
E/flutter (19323): #24 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:591:7)
E/flutter (19323): #25 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (19323): #26 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter (19323):
E/flutter (19323): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unsupported operation: Cannot add to an unmodifiable list
E/flutter (19323): #0 UnmodifiableListMixin.insert (dart:_internal/list.dart:119:5)
E/flutter (19323): #1 TasksBloc._onUpdateTask (package:todo_list/blocs/tasks_bloc/tasks_bloc.dart:45:24)
E/flutter (19323): #2 Bloc.on.<anonymous closure>.handleEvent (package:bloc/src/bloc.dart:226:26)
E/flutter (19323): #3 Bloc.on.<anonymous closure> (package:bloc/src/bloc.dart:235:9)
E/flutter (19323): #4 _MapStream._handleData (dart:async/stream_pipe.dart:213:31)
E/flutter (19323): #5 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (19323): #6 _rootRunUnary (dart:async/zone.dart:1399:47)
E/flutter (19323): #7 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #8 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #9 CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
E/flutter (19323): #10 _rootRunUnary (dart:async/zone.dart:1399:47)
E/flutter (19323): #11 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #12 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #13 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (19323): #14 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (19323): #15 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (19323): #16 _WhereStream._handleData (dart:async/stream_pipe.dart:195:12)
E/flutter (19323): #17 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (19323): #18 _rootRunUnary (dart:async/zone.dart:1407:13)
E/flutter (19323): #19 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #20 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #21 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (19323): #22 _DelayedData.perform (dart:async/stream_impl.dart:515:14)
E/flutter (19323): #23 _PendingEvents.handleNext (dart:async/stream_impl.dart:620:11)
E/flutter (19323): #24 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:591:7)
E/flutter (19323): #25 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (19323): #26 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter (19323):
E/flutter (19323): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unsupported operation: Cannot add to an unmodifiable list
E/flutter (19323): #0 UnmodifiableListMixin.insert (dart:_internal/list.dart:119:5)
E/flutter (19323): #1 TasksBloc._onUpdateTask (package:todo_list/blocs/tasks_bloc/tasks_bloc.dart:45:24)
E/flutter (19323): #2 Bloc.on.<anonymous closure>.handleEvent (package:bloc/src/bloc.dart:226:26)
E/flutter (19323): #3 Bloc.on.<anonymous closure> (package:bloc/src/bloc.dart:235:9)
E/flutter (19323): #4 _MapStream._handleData (dart:async/stream_pipe.dart:213:31)
E/flutter (19323): #5 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (19323): #6 _rootRunUnary (dart:async/zone.dart:1399:47)
E/flutter (19323): #7 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #8 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #9 CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
E/flutter (19323): #10 _rootRunUnary (dart:async/zone.dart:1399:47)
E/flutter (19323): #11 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #12 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #13 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (19323): #14 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (19323): #15 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (19323): #16 _WhereStream._handleData (dart:async/stream_pipe.dart:195:12)
E/flutter (19323): #17 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (19323): #18 _rootRunUnary (dart:async/zone.dart:1407:13)
E/flutter (19323): #19 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (19323): #20 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (19323): #21 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (19323): #22 _DelayedData.perform (dart:async/stream_impl.dart:515:14)
E/flutter (19323): #23 _PendingEvents.handleNext (dart:async/stream_impl.dart:620:11)
E/flutter (19323): #24 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:591:7)
E/flutter (19323): #25 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (19323): #26 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
tasks_bloc.dart
class TasksBloc extends HydratedBloc<TasksEvent, TasksState> {
TasksBloc() : super(const TasksState()) {
on<AddTask>(_onAddTask);
on<UpdateTask>(_onUpdateTask);
on<RemoveTask>(_onRemoveTask);
on<DeleteTask>(_onDeleteTask);
on<MakeFavouriteTask>(_onMakeFavouriteTask);
on<EditTask>(_onEditTask);
on<RestoreTask>(_onRestoreTask);
on<DeleteAllTasks>(_onDeleteAllTasks);
}
void _onAddTask(AddTask event, Emitter<TasksState> emitter) {
final state = this.state;
emitter(
TasksState(
pendingTasks: List.from(state.pendingTasks)..add(event.task),
completedTasks: state.completedTasks,
favouriteTasks: state.favouriteTasks,
deletedTasks: state.deletedTasks,
),
);
}
void _onUpdateTask(UpdateTask event, Emitter<TasksState> emit) {
final state = this.state;
final task = event.task;
List<Task> pendingTasks = state.pendingTasks;
List<Task> completedTasks = state.completedTasks;
List<Task> favouriteTasks = state.favouriteTasks;
if (task.isDone == false) {
if (task.isFavourite == false) {
pendingTasks = List.from(pendingTasks)..remove(task);
completedTasks.insert(0, task.copyWith(isDone: true));
} else {
var taskIndex = favouriteTasks.indexOf(task);
pendingTasks = List.from(pendingTasks)..remove(task);
completedTasks.insert(0, task.copyWith(isDone: true));
favouriteTasks = List.from(favouriteTasks)
..remove(task)
..insert(taskIndex, task.copyWith(isDone: true));
}
} else {
if (task.isFavourite == false) {
completedTasks = List.from(completedTasks)..remove(task);
pendingTasks = List.from(pendingTasks)
..insert(0, task.copyWith(isDone: false));
} else {
var taskIndex = favouriteTasks.indexOf(task);
completedTasks = List.from(completedTasks)..remove(task);
pendingTasks = List.from(pendingTasks)
..insert(0, task.copyWith(isDone: false));
favouriteTasks = List.from(favouriteTasks)
..remove(task)
..insert(taskIndex, task.copyWith(isDone: false));
}
}
emit(TasksState(
pendingTasks: pendingTasks,
completedTasks: completedTasks,
favouriteTasks: favouriteTasks,
deletedTasks: state.deletedTasks,
));
}
void _onRemoveTask(RemoveTask event, Emitter<TasksState> emitter) {
final state = this.state;
emitter(
TasksState(
pendingTasks: state.pendingTasks,
completedTasks: state.completedTasks,
favouriteTasks: state.favouriteTasks,
deletedTasks: List.from(state.deletedTasks)..remove(event.task),
),
);
}
void _onDeleteTask(DeleteTask event, Emitter<TasksState> emitter) {
final state = this.state;
emitter(
TasksState(
pendingTasks: List.from(state.pendingTasks)..remove(event.task),
completedTasks: List.from(state.completedTasks)..remove(event.task),
favouriteTasks: List.from(state.favouriteTasks)..remove(event.task),
deletedTasks: List.from(state.deletedTasks)
..add(
event.task.copyWith(isDeleted: true),
),
),
);
}
void _onMakeFavouriteTask(
MakeFavouriteTask event, Emitter<TasksState> emitter) {
final state = this.state;
List<Task> pendingTasks = state.pendingTasks;
List<Task> completedTasks = state.completedTasks;
List<Task> favouriteTasks = state.favouriteTasks;
if (event.task.isDone == false) {
if (event.task.isFavourite == false) {
var taskIndex = pendingTasks.indexOf(event.task);
pendingTasks = List.from(pendingTasks)
..remove(event.task)
..insert(
taskIndex,
event.task.copyWith(isFavourite: true),
);
favouriteTasks.insert(0, event.task.copyWith(isFavourite: true));
} else {
var taskIndex = pendingTasks.indexOf(event.task);
pendingTasks = List.from(pendingTasks)
..remove(event.task)
..insert(
taskIndex,
event.task.copyWith(isFavourite: false),
);
favouriteTasks.remove(event.task);
}
} else {
if (event.task.isFavourite == false) {
var taskIndex = completedTasks.indexOf(event.task);
completedTasks = List.from(completedTasks)
..remove(event.task)
..insert(
taskIndex,
event.task.copyWith(isFavourite: true),
);
favouriteTasks.insert(
0,
event.task.copyWith(isFavourite: true),
);
} else {
var taskIndex = completedTasks.indexOf(event.task);
completedTasks = List.from(completedTasks)
..remove(event.task)
..insert(
taskIndex,
event.task.copyWith(isFavourite: false),
);
favouriteTasks.remove(event.task);
}
}
emitter(
TasksState(
pendingTasks: pendingTasks,
completedTasks: completedTasks,
favouriteTasks: favouriteTasks,
deletedTasks: state.deletedTasks),
);
}
void _onEditTask(EditTask event, Emitter<TasksState> emitter) {
final state = this.state;
List<Task> favouriteTasks = state.favouriteTasks;
if (event.oldTask.isFavourite == true) {
favouriteTasks
..remove(event.oldTask)
..insert(
0,
event.currentTask,
);
}
emitter(
TasksState(
pendingTasks: List.from(state.pendingTasks)
..remove(event.oldTask)
..insert(0, event.currentTask),
completedTasks: state.completedTasks..remove(event.oldTask),
favouriteTasks: state.favouriteTasks,
deletedTasks: state.deletedTasks,
),
);
}
void _onRestoreTask(RestoreTask event, Emitter<TasksState> emitter) {
final state = this.state;
emitter(
TasksState(
deletedTasks: List.from(state.deletedTasks)..remove(event.task),
pendingTasks: List.from(state.pendingTasks)
..insert(
0,
event.task
.copyWith(isDeleted: false, isDone: false, isFavourite: false),
),
completedTasks: state.completedTasks,
favouriteTasks: state.favouriteTasks,
),
);
}
void _onDeleteAllTasks(DeleteAllTasks event, Emitter<TasksState> emitter) {
final state = this.state;
emitter(TasksState(
deletedTasks: List.from(state.deletedTasks)..clear(),
pendingTasks: state.pendingTasks,
completedTasks: state.completedTasks,
favouriteTasks: state.favouriteTasks,
));
}
#override
TasksState? fromJson(Map<String, dynamic> json) {
return TasksState.fromMap(json);
}
#override
Map<String, dynamic>? toJson(TasksState state) {
return state.toMap();
}
}
class TasksList extends StatelessWidget {
const TasksList({
Key? key,
required this.tasksList,
}) : super(key: key);
final List tasksList;
This tasksList is unmodifiable.
WHat you'd want to do is listen/get new data from the bloc
using context.watch<TasksBloc>().completedTasks
e.g
Sample usage.
class TasksList extends StatelessWidget {
const TasksList({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final tasksList =context.watch<TasksBloc>().completedTasks;
return ListView.builder(
padding: const EdgeInsets.only(top: 20),
itemCount: tasksList.length,
itemBuilder: (context, index) {
var task = tasksList[index];
return TaskTile(task: task);
},
);
}
}

TabBarView displays properly with Flutter debug but not with release

TabBarView displays properly with Flutter debug but not with release
Windows11 / Flutter 3.0.1 / Getx 4.6.5
flutter run --release output:
I/flutter (31177): Null check operator used on a null value
I/flutter (31177): #0 _PagePosition.applyViewportDimension (package:flutter/src/widgets/page_view.dart:455)
I/flutter (31177): #1 RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1456)
I/flutter (31177): #2 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #3 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #4 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #5 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #6 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #7 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #8 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #9 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #10 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #11 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #12 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #13 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #14 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #15 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #16 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #17 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #18 RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545)
I/flutter (31177): #19 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #20 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #21 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #22 MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:171)
I/flutter (31177): #23 _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:1003)
I/flutter (31177): #24 MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:240)
I/flutter (31177): #25 RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:403)
I/flutter (31177): #26 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #27 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #28 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #29 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #30 _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1376)
I/flutter (31177): #31 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #32 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #33 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #34 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #35 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #36 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #37 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #38 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #39 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #40 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #41 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #42 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #43 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #44 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #45 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #46 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #47 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #48 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #49 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #50 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #51 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #52 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #53 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #54 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #55 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #56 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #57 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #58 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #59 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #60 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #61 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #62 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #63 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #64 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #65 RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3462)
I/flutter (31177): #66 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #67 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #68 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #69 _RenderTheatre.performLayout (package:flutter/src/widgets/overlay.dart:749)
I/flutter (31177): #70 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #71 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #72 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #73 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #74 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #75 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #76 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #77 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #78 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #79 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #80 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #81 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #82 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #83 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116)
I/flutter (31177): #84 RenderObject.layout (package:flutter/src/rendering/object.dart:1915)
I/flutter (31177): #85 RenderView.performLayout (package:flutter/src/rendering/view.dart:165)
I/flutter (31177): #86 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1757)
I/flutter (31177): #87 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:887)
I/flutter (31177): #88 RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:504)
I/flutter (31177): #89 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:892)
I/flutter (31177): #90 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:370)
I/flutter (31177): #91 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1146)
I/flutter (31177): #92 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1083)
I/flutter (31177): #93 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:997)
I/flutter (31177): #97 _invoke (dart:ui/hooks.dart:151)
I/flutter (31177): #98 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308)
I/flutter (31177): #99 _drawFrame (dart:ui/hooks.dart:115)
I/flutter (31177): (elided 3 frames from dart:async)
main.dart
import 'package:get/get.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: RouteConfig.home,
getPages: RouteConfig.getPages,
);
}
}
class RouteConfig {
static const String home = "/home";
static final List<GetPage> getPages = [
GetPage(
name: home,
page: () => const HomePage(),
binding: HomeBinding(),
)
];
}
//----------------------------------------------------home------------------------------------
class HomeBinding extends Bindings {
#override
void dependencies() {
Get.lazyPut(() => HomeController());
}
}
class HomeController extends GetxController
with GetSingleTickerProviderStateMixin {
final List<Tab> tabs = <Tab>[const Tab(text: 'Movie'), const Tab(text: 'Tv')];
late TabController tabController;
#override
void onInit() {
debugPrint("HomeController onInit");
super.onInit();
tabController = TabController(vsync: this, length: tabs.length);
tabController.addListener(() {
debugPrint(
"TabController listen, index:${tabController.index}, len:${tabController.length}");
});
}
#override
void onClose() {
debugPrint("HomeController onClose");
tabController.dispose();
super.onClose();
}
}
class HomePage extends GetView<HomeController> {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return GetBuilder<HomeController>(
builder: (logic) {
return Scaffold(
appBar: AppBar(
leading: const Icon(
Icons.home,
),
title: const Text('Home'),
centerTitle: true,
actions: [
IconButton(
icon: const Icon(Icons.search),
color: Colors.white,
onPressed: () {
debugPrint("search");
},
),
],
bottom: TabBar(
isScrollable: true,
indicatorWeight: 1,
indicatorSize: TabBarIndicatorSize.tab,
indicatorColor: Colors.white,
controller: logic.tabController,
tabs: logic.tabs,
onTap: (index) {
debugPrint("TabBar index: $index");
},
),
),
body: TabBarView(
controller: logic.tabController,
children: logic.tabs.map((tab) {
debugPrint("create TabBarView, tab:${tab.text}");
if (tab.text == null) {
return const Center(child: Text("default"));
}
if (tab.text == "Movie") {
return const StatefulMoviePage();
}
return Center(child: Text(tab.text!));
}).toList(),
),
);
},
);
}
}
//----------------------------------------------------movie------------------------------------
class Movie {
int id = 0;
String name = "";
String image = "";
Movie(this.id, this.name, this.image);
}
class MovieState {
late List<Movie> movies;
MovieState() {
movies = <Movie>[];
}
}
class MovieController extends GetxController {
final state = MovieState();
#override
void onInit() {
debugPrint("MovieController onInit");
super.onInit();
state.movies = <Movie>[
Movie(1, "movie1", "/files/1"),
Movie(2, "movie2", "/files/1"),
Movie(3, "movie3", "/files/1"),
];
}
}
class StatefulMoviePage extends StatefulWidget {
const StatefulMoviePage({Key? key}) : super(key: key);
#override
StatefulMoviePageState createState() => StatefulMoviePageState();
}
class StatefulMoviePageState extends State<StatefulMoviePage>
with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
debugPrint("StatefulMoviePageState build start");
super.build(context);
return const MoviePage();
}
#override
bool get wantKeepAlive => true;
}
class MoviePage extends GetView<MovieController> {
const MoviePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
debugPrint("MoviePage build start");
Get.put(MovieController());
return GetBuilder<MovieController>(
builder: (c) {
debugPrint("movies: ${c.state.movies.length}");
return ListView(
children: c.state.movies.map((Movie m) {
return ListTile(title: Text(m.name));
}).toList(),
);
},
);
}
}
tldr: add a delay to give tabbar view time to Initialise, add async to main with
await Future.delayed(const Duration(milliseconds: XXX));
I also had this issue when running in release mode, (worked fine in debug).
It seems the problem is the widget is not properly initialized, so you have to wait or give some delay when you run your app in the main() function
Maybe this would help:
Instead of this:
void main() {
WidgetsFlutterBinding.ensureInitialized();
NotificationService().initNotification();
runApp(const MainPage());
}
You can have:
void main() async{
WidgetsFlutterBinding.ensureInitialized();
NotificationService().initNotification();
await Future.delayed(const Duration(milliseconds: 300));
runApp(const MainPage());
}

Riverpod select() runs before list view children are rebuilt

I am using Riverpod (package:flutter_riverpod v1.0.3) to manage state in my Flutter app. I would like to have a list of Widgets built based on the items in a model. Each list item Widget uses provider.select to pick the corresponding model item at its index. See the following example app:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(const MyApp());
}
final provider = StateNotifierProvider<FruitStateNotifier, List<String>>((ref) {
return FruitStateNotifier(['apricot', 'blueberry', 'cherry']);
});
class FruitStateNotifier extends StateNotifier<List<String>> {
FruitStateNotifier(List<String> fruits) : super(fruits);
void update(List<String> fruits) => state = fruits;
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const ProviderScope(
child: MaterialApp(
home: Scaffold(
body: FruitList(),
),
),
);
}
}
class FruitList extends ConsumerWidget {
const FruitList({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
return ListView.builder(
itemCount: ref.watch(provider.select((p) => p.length)),
itemBuilder: (context, index) {
return ListTile(
title: Text('$index) ${ref.watch(provider.select((p) => p[index]))}'),
trailing: IconButton(
onPressed: () {
final fruits = ref.read(provider);
final newFruits = List.of(fruits)..removeAt(index);
ref.read(provider.notifier).update(newFruits);
},
icon: const Icon(Icons.delete),
),
);
},
);
}
}
However, when deleting an element, the select functions are run, but it seems that the ListView's item count has not yet been updated to match the model's item count. This causes the last Widget in the list to have no corresponding model item, and so we get an error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: An exception was thrown while building StateNotifierProvider<FruitStateNotifier, List<String>>#82be7.
Thrown exception:
RangeError (index): Invalid value: Not in inclusive range 0..1: 2
Stack trace:
#0 List.[] (dart:core-patch/growable_array.dart:281:36)
#1 FruitList.build.<anonymous closure>.<anonymous closure>
#2 _ProviderSelector._select.<anonymous closure>
#3 ResultData.map
#4 _ProviderSelector._select
#5 _ProviderSelector._selectOnChange
#6 _ProviderSelector.listen.<anonymous closure>
#7 _rootRunBinary (dart:async/zone.dart:1450:47)
#8 _CustomZone.runBinary (dart:async/zone.dart:1342:19)
#9 _CustomZone.runBinaryGuarded (dart:async/zone.dart:1252:7)
#10 ProviderElementBase._notifyListeners.<anonymous closure>
#11 ResultData.map
#12 ProviderElementBase._notifyListeners
#13 ProviderElementBase.setState
#14 StateNotifierProvider.create.listener
#15 StateNotifier.state=
#16 FruitStateNotifier.update
#17 FruitList.build.<anonymous closure>.<anonymous closure>
#18 _InkResponseState._handleTap
#19 GestureRecognizer.invokeCallback
#20 TapGestureRecognizer.handleTapUp
#21 BaseTapGestureRecognizer._checkUp
#22 BaseTapGestureRecognizer.handlePrimaryPointer
#23 PrimaryPointerGestureRecognizer.handleEvent
#24 PointerRouter._dispatch
#25 PointerRouter._dispatchEventToRoutes.<anonymous closure>
#26 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
#27 PointerRouter._dispatchEventToRoutes
#28 PointerRouter.route
#29 GestureBinding.handleEvent
#30 GestureBinding.dispatchEvent
#31 RendererBinding.dispatchEvent
#32 GestureBinding._handlePointerEventImmediately
#33 GestureBinding.handlePointerEvent
#34 GestureBinding._flushPointerEventQueue
#35 GestureBinding._handlePointerDataPacket
#36 _rootRunUnary (dart:async/zone.dart:1442:13)
#37 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
#38 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
#39 _invoke1 (dart:ui/hooks.dart:170:10)
#40 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#41 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
#0 _fallbackOnErrorForProvider
#1 _ProviderSelector.listen
#2 ProviderContainer.listen
#3 ConsumerStatefulElement.watch.<anonymous closure>
#4 _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:453:23)
#5 ConsumerStatefulElement.watch
#6 FruitList.build.<anonymous closure>
#7 SliverChildBuilderDelegate.build
#8 SliverMultiBoxAdaptorElement._build
#9 SliverMultiBoxAdaptorElement.createChild.<anonymous closure>
#10 BuildOwner.buildScope
#11 SliverMultiBoxAdaptorElement.createChild
#12 RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure>
#13 RenderObject.invokeLayoutCallback.<anonymous closure>
#14 PipelineOwner._enableMutationsToDirtySubtrees
#15 RenderObject.invokeLayoutCallback
#16 RenderSliverMultiBoxAdaptor._createOrObtainChild
#17 RenderSliverMultiBoxAdaptor.insertAndLayoutChild
#18 RenderSliverList.performLayout.advance
#19 RenderSliverList.performLayout
#20 RenderObject.layout
#21 RenderSliverEdgeInsetsPadding.performLayout
#22 RenderSliverPadding.performLayout
#23 RenderObject.layout
#24 RenderViewportBase.layoutChildSequence
#25 RenderViewport._attemptLayout
#26 RenderViewport.performLayout
#27 RenderObject.layout
#28 RenderProxyBoxMixin.performLayout
#29 RenderObject.layout
#30 RenderProxyBoxMixin.performLayout
#31 RenderObject.layout
#32 RenderProxyBoxMixin.performLayout
#33 RenderObject.layout
#34 RenderProxyBoxMixin.performLayout
#35 RenderObject.layout
#36 RenderProxyBoxMixin.performLayout
#37 RenderObject.layout
#38 RenderProxyBoxMixin.performLayout
#39 RenderObject.layout
#40 RenderProxyBoxMixin.performLayout
#41 RenderObject.layout
#42 RenderProxyBoxMixin.performLayout
#43 RenderCustomPaint.performLayout
#44 RenderObject.layout
#45 RenderProxyBoxMixin.performLayout
#46 RenderObject.layout
#47 RenderProxyBoxMixin.performLayout
#48 RenderObject.layout
#49 RenderProxyBoxMixin.performLayout
#50 RenderObject.layout
#51 RenderProxyBoxMixin.performLayout
#52 RenderObject.layout
#53 MultiChildLayoutDelegate.layoutChild
#54 _ScaffoldLayout.performLayout
#55 MultiChildLayoutDelegate._callPerformLayout
#56 RenderCustomMultiChildLayoutBox.performLayout
#57 RenderObject.layout
#58 RenderProxyBoxMixin.performLayout
#59 RenderObject.layout
#60 RenderProxyBoxMixin.performLayout
#61 _RenderCustomClip.performLayout
#62 RenderObject.layout
#63 RenderProxyBoxMixin.performLayout
#64 RenderObject.layout
#65 RenderProxyBoxMixin.performLayout
#66 RenderObject.layout
#67 RenderProxyBoxMixin.performLayout
#68 RenderObject.layout
#69 RenderProxyBoxMixin.performLayout
#70 RenderObject.layout
#71 RenderProxyBoxMixin.performLayout
#72 RenderObject.layout
#73 RenderProxyBoxMixin.performLayout
#74 RenderObject.layout
#75 RenderProxyBoxMixin.performLayout
#76 RenderObject.layout
#77 RenderProxyBoxMixin.performLayout
#78 RenderObject.layout
#79 RenderProxyBoxMixin.performLayout
#80 RenderOffstage.performLayout
#81 RenderObject.layout
#82 RenderProxyBoxMixin.performLayout
#83 RenderObject.layout
#84 _RenderTheatre.performLayout
#85 RenderObject.layout
#86 RenderProxyBoxMixin.performLayout
#87 RenderObject.layout
#88 RenderProxyBoxMixin.performLayout
#89 RenderObject.layout
#90 RenderProxyBoxMixin.performLayout
#91 RenderObject.layout
#92 RenderProxyBoxMixin.performLayout
#93 RenderCustomPaint.performLayout
#94 RenderObject.layout
#95 RenderProxyBoxMixin.performLayout
#96 RenderObject.layout
#97 RenderProxyBoxMixin.performLayout
#98 RenderObject.layout
#99 RenderProxyBoxMixin.performLayout
#100 RenderObject.layout
#101 RenderProxyBoxMixin.performLayout
#102 RenderObject.layout
#103 RenderView.performLayout
#104 RenderObject._layoutWithoutResize
#105 PipelineOwner.flushLayout
#106 RendererBinding.drawFrame
#107 WidgetsBinding.drawFrame
#108 RendererBinding._handlePersistentFrameCallback
#109 SchedulerBinding._invokeFrameCallback
#110 SchedulerBinding.handleDrawFrame
#111 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure>
#112 _rootRun (dart:async/zone.dart:1418:47)
#113 _CustomZone.run (dart:async/zone.dart:1328:19)
#114 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
#115 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
#116 _rootRun (dart:async/zone.dart:1426:13)
#117 _CustomZone.run (dart:async/zone.dart:1328:19)
#118 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1260:23)
#119 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
#120 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19)
#121 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5)
#122 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
How can I build the list and its children without this issue?
Using select here does not really make sense, you are not optimizing rebuilds, since it will be rebuilt when the number of items in the list changes anyway.
The best you can do here is just watch the state once and assign it to a variable:
final fruitList = ref.watch(provider);
Then just use the variable to get the length and build the list items.
So the resulting code will be:
class FruitList extends ConsumerWidget {
const FruitList({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final fruitList = ref.watch(provider);
return ListView.builder(
itemCount: fruitList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('$index) ${fruitList[index]}'),
trailing: IconButton(
onPressed: () {
final newFruits = List.of(fruitList)..removeAt(index);
ref.read(provider.notifier).update(newFruits);
},
icon: const Icon(Icons.delete),
),
);
},
);
}
}
Try this:
class FruitList extends ConsumerWidget {
const FruitList({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final list = ref.watch(provider);
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('$index) ${list[index]}'),
trailing: IconButton(
onPressed: () {
final fruits = ref.read(provider);
final newFruits = List.of(fruits)..removeAt(index);
ref.read(provider.notifier).update(newFruits);
},
icon: const Icon(Icons.delete),
),
);
},
);
}
}
I created a todo app using riverpod, so I used ref.watch(todoController.select((value) => value.length) to rebuild todo listView whenever todo list length changes, but for update I used ref.watch(todoController.select((value) => value[index]) to rebuild only that listTile whose item changes, it was working fine but when deleted any item was getting the invalid range error, so what i did is that in ListTile provider.select added a condition
todoController.select((value) => value.length > index ? value[index]: null),
and now not getting error on deleting, on update only listTile rebuild which needs to and on creating and delete whole listview rebuild w/o invalid range exception
class TodosListWidget extends ConsumerWidget {
const TodosListWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
print('rebuild todo List');
final todosItem = ref.watch(todoController.select((value) => value.length));
return ListView.builder(
itemCount: todosItem,
itemBuilder: ((context, index) => TodoWidget(index: index,)
));
}
}
class TodoWidget extends ConsumerWidget {
final int index;
const TodoWidget({required this.index, Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final currentTodo =
ref.watch(todoController.select((value) => value.length > index ? value[index]: null));
print('rebuild Current todo');
return InkWell(
onDoubleTap: () => ref
.read(todoController.notifier)
.deleteTodo(currentTodo!.id),
onTap: () => ref
.read(todoController.notifier)
.updateTodo('change', 'todo is changed', currentTodo!.id),
child: ListTile(
title: Text(currentTodo!.name),
subtitle: Text(currentTodo.desc),
),
);
}
}

Flutter Provider Null check operator used on a null value

I did a very simple provider test, but I keep getting this error. I switched to flutter stable channel, upgraded, and cleaned it. the result is the same.
It gives this error when I write the function to dispose method of any screen.
My purpose for using the dipsos method:
Disposal of ValueNotifiers: It's always a good practice to dispose all
the ValueNotifiers once they are no longer in use which can save the
app from memory loss.
I want current subscriptions to expire when I exit the screen for performance. I create a new valuenotifier when the screen is initialize and I want to dispose when I exit the screen.
main.dart file
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ScreenChangeNotifier(),),
Provider(create: (context) => Genel(),)
],
child: MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue
),
title: 'Test',
home: HomeScreen(),
),
);
}
}
ScreenChangeNotifier.dart file
class ScreenChangeNotifier extends ChangeNotifier
{
void hello() => print("say hello");
}
HomeScreen.dart file
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
void dispose() {
context.read<ScreenChangeNotifier>().hello();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(),
);
}
}
this error
======== Exception caught by widgets library =======================================================
The following _CastError was thrown while finalizing the widget tree:
Null check operator used on a null value
When the exception was thrown, this was the stack:
#0 Element.widget (package:flutter/src/widgets/framework.dart:3203:31)
#1 Provider._inheritedElementOf (package:provider/src/provider.dart:341:17)
#2 Provider.of (package:provider/src/provider.dart:293:30)
#3 ReadContext.read (package:provider/src/provider.dart:656:21)
#4 _HomeScreenState.dispose (package:bencebilirpro/screens/HomeScreen.dart:11:13)
#5 StatefulElement.unmount (package:flutter/src/widgets/framework.dart:4983:11)
#6 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1926:13)
#7 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#8 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#9 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#10 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#11 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#12 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#13 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#14 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#15 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#16 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#17 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#18 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#19 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#20 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#21 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#22 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#23 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#24 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#25 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#26 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#27 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#28 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#29 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#30 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#31 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#32 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#33 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#34 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#35 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#36 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#37 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#38 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#39 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#40 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#41 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#42 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#43 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#44 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#45 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#46 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#47 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#48 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#49 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#50 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#51 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#52 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#53 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#54 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#55 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#56 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#57 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#58 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#59 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#60 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#61 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#62 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#63 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#64 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#65 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#66 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#67 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#68 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#69 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#70 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#71 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#72 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#73 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#74 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#75 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#76 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#77 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#78 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#79 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#80 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#81 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#82 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#83 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#84 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#85 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#86 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6271:14)
#87 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#88 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#89 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#90 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#91 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#92 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#93 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#94 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1924:7)
#95 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4807:14)
#96 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1922:13)
#97 ListIterable.forEach (dart:_internal/iterable.dart:39:13)
#98 _InactiveElements._unmountAll (package:flutter/src/widgets/framework.dart:1935:25)
#99 BuildOwner.lockState (package:flutter/src/widgets/framework.dart:2519:15)
#100 BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:2932:7)
#101 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:884:19)
#102 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#103 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#104 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9)
#105 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:995:5)
#109 _invoke (dart:ui/hooks.dart:151:10)
#110 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#111 _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)
====================================================================================================
First of all, why you call your method in the dispose() method? dispose called when this object is removed from the tree permanently, you shouldn't try to find ancestors of this widget at this point because your widget is already deleted from the widget tree.
If you want to do that anyway, try to create variable in State, initialize it in initState() with context.read<ScreenChangeNotifier>() and in dispose call variable.hello()
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
ScreenChangeNotifier _notifier;
#override
void initState() {
_notifier = context.read<ScreenChangeNotifier>();
super.initState();
}
#override
void dispose() {
_notifier.hello();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(),
);
}
}
Why you are calling ScreenChangeNotifier in dispose function? You have to call it in initstate or inside build method.
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
void initState() {
super.initState();
context.read<ScreenChangeNotifier>().hello();
}
#override
Widget build(BuildContext context) {
// or you can call it here..
// context.read<ScreenChangeNotifier>().hello();
return Scaffold(
body: Container(),
);
}
}

Flutter AnimatedBuilder builder bug

The following sample code does something unexpected:
import 'package:characters/characters.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
print(' *** _MyHomePageState:_incrementCounter - ${this.hashCode}');
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Animated Text Kit Issue 168')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedTextKit(
animatedText: TypewriterAnimatedText(
'Animated Text',
textStyle: const TextStyle(
fontSize: 45.0,
fontWeight: FontWeight.w900,
color: Colors.pink,
),
),
),
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
/// Animated Text that displays a [Text] element as if it is being typed one
/// character at a time.
class TypewriterAnimatedText {
/// Text for [Text] widget.
final String text;
/// [TextStyle] property for [Text] widget.
final TextStyle textStyle;
/// The [Duration] of the delay between the apparition of each characters
///
/// By default it is set to 30 milliseconds.
final Duration speed;
/// The Duration for the Animation Controller.
final Duration duration;
/// Same as [text] but as [Characters].
///
/// Need to use character length, not String length, to propertly support
/// Unicode and Emojis.
final Characters textCharacters;
TypewriterAnimatedText(
this.text, {
#required this.textStyle,
this.speed = const Duration(milliseconds: 30),
}) : assert(null != speed),
textCharacters = text.characters,
duration = speed * (text.characters.length);
Animation<int> _typewriterText;
void initAnimation(AnimationController controller) {
print(' >>> TypewriterAnimatedText:initAnimation - ${this.hashCode}');
_typewriterText = StepTween(
begin: 0,
end: textCharacters.length,
).animate(controller);
}
/// Widget showing partial text
Widget animatedBuilder(BuildContext context, Widget child) {
print(' >>> TypewriterAnimatedText:animatedBuilder - ${this.hashCode}');
final typewriterValue = _typewriterText.value;
final visibleString = '${textCharacters.take(typewriterValue)}_';
return Text(visibleString, style: textStyle);
}
}
/// Base class for Animated Text widgets.
class AnimatedTextKit extends StatefulWidget {
/// Text animation.
final TypewriterAnimatedText animatedText;
const AnimatedTextKit({
Key key,
#required this.animatedText,
}) : super(key: key);
/// Creates the mutable state for this widget. See [StatefulWidget.createState].
#override
_AnimatedTextKitState createState() => _AnimatedTextKitState();
}
class _AnimatedTextKitState extends State<AnimatedTextKit>
with TickerProviderStateMixin {
AnimationController _controller;
#override
void initState() {
print(' ^^^ _AnimatedTextKitState:initState - ${this.hashCode}');
super.initState();
final animatedText = widget.animatedText;
_controller = AnimationController(
duration: animatedText.duration,
vsync: this,
);
animatedText.initAnimation(_controller);
_controller.repeat();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
print(' ^^^ _AnimatedTextKitState:build - ${this.hashCode}');
return AnimatedBuilder(
animation: _controller,
builder: widget.animatedText.animatedBuilder,
);
}
}
Run it and click on the Floating Action Button to increment the counter and the output will look something like this:
I/flutter (29275): ^^^ _AnimatedTextKitState:initState - 171683441
I/flutter (29275): >>> TypewriterAnimatedText:initAnimation - 936400533
I/flutter (29275): ^^^ _AnimatedTextKitState:build - 171683441
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 936400533
I/chatty (29275): uid=10133(com.example.atk168) 1.ui identical 2 lines
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 936400533
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 936400533
I/chatty (29275): uid=10133(com.example.atk168) 1.ui identical 60 lines
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 936400533
I/flutter (29275): *** _MyHomePageState:_incrementCounter - 220007591
I/flutter (29275): ^^^ _AnimatedTextKitState:build - 171683441
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 280798896
I/flutter (29275): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (29275): The following NoSuchMethodError was thrown building AnimatedBuilder(animation:
I/flutter (29275): AnimationController#41b74(▶ 0.633), dirty, state: _AnimatedState#db314):
I/flutter (29275): The getter 'value' was called on null.
I/flutter (29275): Receiver: null
I/flutter (29275): Tried calling: value
I/flutter (29275):
I/flutter (29275): The relevant error-causing widget was:
I/flutter (29275): AnimatedBuilder file:///Users/anthony/github/awhitford/atk168/lib/main.dart:173:12
I/flutter (29275):
I/flutter (29275): When the exception was thrown, this was the stack:
I/flutter (29275): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
I/flutter (29275): #1 TypewriterAnimatedText.animatedBuilder (package:atk168/main.dart:121:45)
I/flutter (29275): #2 AnimatedBuilder.build (package:flutter/src/widgets/transitions.dart:1528:19)
I/flutter (29275): #3 _AnimatedState.build (package:flutter/src/widgets/transitions.dart:179:48)
I/flutter (29275): #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4825:27)
I/flutter (29275): #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4708:15)
I/flutter (29275): #6 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #7 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #8 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #9 StatefulElement.update (package:flutter/src/widgets/framework.dart:4912:5)
I/flutter (29275): #10 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #12 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #13 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #14 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #15 StatefulElement.update (package:flutter/src/widgets/framework.dart:4912:5)
I/flutter (29275): #16 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #17 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5727:32)
I/flutter (29275): #18 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6327:17)
I/flutter (29275): #19 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #20 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6205:14)
I/flutter (29275): #21 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #22 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #23 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #24 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #25 StatelessElement.update (package:flutter/src/widgets/framework.dart:4789:5)
I/flutter (29275): #26 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #27 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #28 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #29 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #30 ProxyElement.update (package:flutter/src/widgets/framework.dart:5066:5)
I/flutter (29275): #31 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #32 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #33 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #34 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #35 ProxyElement.update (package:flutter/src/widgets/framework.dart:5066:5)
I/flutter (29275): #36 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #37 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5727:32)
I/flutter (29275): #38 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6327:17)
I/flutter (29275): #39 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #40 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #41 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #42 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #43 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #44 StatefulElement.update (package:flutter/src/widgets/framework.dart:4912:5)
I/flutter (29275): #45 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #46 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #47 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #48 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #49 ProxyElement.update (package:flutter/src/widgets/framework.dart:5066:5)
I/flutter (29275): #50 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #51 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #52 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #53 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #54 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #55 StatefulElement.update (package:flutter/src/widgets/framework.dart:4912:5)
I/flutter (29275): #56 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #57 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6205:14)
I/flutter (29275): #58 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #59 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #60 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #61 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #62 StatelessElement.update (package:flutter/src/widgets/framework.dart:4789:5)
I/flutter (29275): #63 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #64 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6205:14)
I/flutter (29275): #65 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #66 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #67 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #68 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #69 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #70 StatefulElement.update (package:flutter/src/widgets/framework.dart:4912:5)
I/flutter (29275): #71 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #72 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #73 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #74 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #75 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #76 StatefulElement.update (package:flutter/src/widgets/framework.dart:4912:5)
I/flutter (29275): #77 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #78 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #79 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #80 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #81 ProxyElement.update (package:flutter/src/widgets/framework.dart:5066:5)
I/flutter (29275): #82 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #83 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #84 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #85 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #86 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #87 StatefulElement.update (package:flutter/src/widgets/framework.dart:4912:5)
I/flutter (29275): #88 Element.updateChild (package:flutter/src/widgets/framework.dart:3412:15)
I/flutter (29275): #89 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4733:16)
I/flutter (29275): #90 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4880:11)
I/flutter (29275): #91 BuildOwner._runWithCurrentBuildTarget (package:flutter/src/widgets/framework.dart:2708:15)
I/flutter (29275): #92 Element.rebuild (package:flutter/src/widgets/framework.dart:4407:12)
I/flutter (29275): #93 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2813:33)
I/flutter (29275): #94 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:899:21)
I/flutter (29275): #95 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:320:5)
I/flutter (29275): #96 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1119:15)
I/flutter (29275): #97 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1057:9)
I/flutter (29275): #98 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:973:5)
I/flutter (29275): #102 _invoke (dart:ui/hooks.dart:157:10)
I/flutter (29275): #103 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:253:5)
I/flutter (29275): #104 _drawFrame (dart:ui/hooks.dart:120:31)
I/flutter (29275): (elided 3 frames from dart:async)
I/flutter (29275):
I/flutter (29275): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (29275): Another exception was thrown: A RenderFlex overflowed by 99320 pixels on the bottom.
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 280798896
I/flutter (29275): Another exception was thrown: NoSuchMethodError: The getter 'value' was called on null.
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 280798896
Application finished.
Specifically, look closely at this:
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 936400533
I/flutter (29275): *** _MyHomePageState:_incrementCounter - 220007591
I/flutter (29275): ^^^ _AnimatedTextKitState:build - 171683441
I/flutter (29275): >>> TypewriterAnimatedText:animatedBuilder - 280798896
I/flutter (29275): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (29275): The following NoSuchMethodError was thrown building AnimatedBuilder(animation:
I/flutter (29275): AnimationController#41b74(▶ 0.633), dirty, state: _AnimatedState#db314):
I/flutter (29275): The getter 'value' was called on null.
I/flutter (29275): Receiver: null
I/flutter (29275): Tried calling: value
I/flutter (29275):
I/flutter (29275): The relevant error-causing widget was:
I/flutter (29275): AnimatedBuilder file:///Users/anthony/github/awhitford/atk168/lib/main.dart:173:12
I/flutter (29275):
I/flutter (29275): When the exception was thrown, this was the stack:
I/flutter (29275): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
I/flutter (29275): #1 TypewriterAnimatedText.animatedBuilder (package:atk168/main.dart:121:45)
I/flutter (29275): #2 AnimatedBuilder.build (package:flutter/src/widgets/transitions.dart:1528:19)
I/flutter (29275): #3 _AnimatedState.build (package:flutter/src/widgets/transitions.dart:179:48)
I only have one TypewriterAnimatedText declaration. It is building TypewriterAnimatedText 936400533, which has been properly initialized, but after clicking the button, it starts building a new instance (280798896) that hasn't been initialized, and so _typewriterText is null, and calling .value on that triggers this issue.
What is going on? I'm expecting that build only runs after initState -- but that doesn't seem to be the case here? (Did I discover a Flutter Bug?)
This issue was a little tricky to reproduce. I received several complaints from Windows users, so it would seem that they were able to easily reproduce this. For myself, I was only able to reproduce this on my Mac after switching to the dev channel and testing on the Android emulator.