Skip to content

Instantly share code, notes, and snippets.

@tg21
Created October 1, 2020 09:37
Show Gist options
  • Save tg21/5a09fcb1f5fd2efdcbb1da4fac2d469e to your computer and use it in GitHub Desktop.
Save tg21/5a09fcb1f5fd2efdcbb1da4fac2d469e to your computer and use it in GitHub Desktop.
SetState not rendering when List are involved
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 10;
int val = 1;
List<Widget> l1 = [];
List<int> l2 = [];
void start() {
for(var i=0;i<_counter;i++){
setState((){
l2.add(val);
l1.add(
Text(l2[i].toString())
);
val++;
});
}
Timer.periodic(Duration(milliseconds: 1000),(timer){
for(var i=0;i<_counter;i++){
setState((){
l2[i]++;
});
print(l2[i]);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children:[
Text("0"),
...l1,
]
),
floatingActionButton: FloatingActionButton(
onPressed: start,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment