How to pass data between Widgets - flutter

I've the below code where I fetch correctly data from url, display it in DataTable, and get the idext of the tapped row.
I need to use this index and display the related information on the back of the widget, I cam across TweenAnimationBuilder but not sure how to send data between the 2 faces, or if there is another way to do what I'm looking for:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:csv/csv.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(title: 'Flutter Demo Home Page'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_AppState createState() => _AppState();
}
Future<List<List<dynamic>>> fetchUserData() async {
final request = await HttpClient().getUrl(Uri.parse(
'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
final response = await request.close();
List<List<dynamic>> rowsAsListOfValues;
await for (final csvString in response.transform(const Utf8Decoder())) {
rowsAsListOfValues = const CsvToListConverter().convert(csvString);
}
return rowsAsListOfValues;
}
class _AppState extends State<HomePage> {
List<List<dynamic>> rowsAsListOfValues;
// ScrollController _controller;
#override
void didChangeDependencies() async {
super.didChangeDependencies();
rowsAsListOfValues = await fetchUserData();
super.setState(() {}); // to update widget data
}
#override
void initState() {
super.initState();
// _controller = ScrollController();
// _controller = new ScrollController()..addListener(_scrollListener);
}
/*
void _scrollListener() {
if (_controller.position.extentAfter <= 0.0 &&
_controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange) {
print("call fetch method again");
}
} */
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
rowsAsListOfValues == null
? Text("Loading data...")
: Text(
'', // $rowsAsListOfValues
),
rowsAsListOfValues == null
? CircularProgressIndicator()
: DataTable(
showCheckboxColumn: false, // <-- this is important
columns: const <DataColumn>[
DataColumn(
label: Text(
'City',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Branches',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: List.generate(rowsAsListOfValues.length - 1, (index) {
return DataRow(
onSelectChanged: (bool selected) {
if (selected) {
print('index-selected: ${rowsAsListOfValues[index + 1][0]}');
}
},
cells: <DataCell>[
// DataCell(Text('${rowsAsListOfValues[index + 1][0]}')), // Index
DataCell(Text('${rowsAsListOfValues[index + 1][1]}')), // city
DataCell(Text('${rowsAsListOfValues[index + 1][2]}')), // branch
],
);
}),
),
],
),
),
);
}
}

May be you can use this https://pub.dev/packages/flippable_box flutter plugin which gives you options to define different view for front and back. You can use _isFlipped variable to maintain which side you want to display.
FlippableBox(
front: Data table for front view,
back: Display selected row,
isFlipped: _isFlipped,
)

Related

Can I use Google sheet as data source for my mobile app

Using Dart language and Flutter, is there a way that I can use the data saved in my google sheet as source data for my mobile application using Dart/Flutter without downloading offline copy of the file?
Yes, this is possible, with the below steps:
In Googlesheets:
Publish the sheet under consideration as csv file, using File -> Publish to the web, make sure to select the option "Automatically republish when changes are made"
Copy the link provided by googleSheets for the csv connectivity
In Flutter/Dart use the below code:
Read data from the csv url generated above using final request = await HttpClient().getUrl(Uri.parse( 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
Convert the returned string into csv as rowsAsListOfValues = const CsvToListConverter().convert(csvString);
Display the data using DataTable(columns: const <DataColumn>[],rows: List.generate(rowsAsListOfValues.length - 1, (index) {return DataRow(cells: <DataCell>[DataCell())],
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:csv/csv.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(title: 'Flutter Demo Home Page'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_AppState createState() => _AppState();
}
Future<List<List<dynamic>>> fetchUserData() async {
final request = await HttpClient().getUrl(Uri.parse(
'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
final response = await request.close();
List<List<dynamic>> rowsAsListOfValues;
await for (final csvString in response.transform(const Utf8Decoder())) {
rowsAsListOfValues = const CsvToListConverter().convert(csvString);
}
return rowsAsListOfValues;
}
class _AppState extends State<HomePage> {
List<List<dynamic>> rowsAsListOfValues;
#override
void didChangeDependencies() async {
super.didChangeDependencies();
rowsAsListOfValues = await fetchUserData();
super.setState(() {}); // to update widget data
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
rowsAsListOfValues == null
? Text("Loading data...")
: Text(
'', // $rowsAsListOfValues
),
rowsAsListOfValues == null
? CircularProgressIndicator()
: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'City',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Branches',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: List.generate(rowsAsListOfValues.length - 1, (index) {
return DataRow(
cells: <DataCell>[
DataCell(Text('${rowsAsListOfValues[index + 1][0]}')),
DataCell(Text('${rowsAsListOfValues[index + 1][1]}')),
],
);
})),
],
),
),
);
}
}

Showing detailed data of of selected cell at DataTable

I've the below code that is fetching data from url and display it in a DataTable.
I want to add more functionality to my code so that more details popingup based on the selected id or field, for example:
If I pressed the line, I need to read the hidden ID number
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:csv/csv.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(title: 'Flutter Demo Home Page'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_AppState createState() => _AppState();
}
Future<List<List<dynamic>>> fetchUserData() async {
final request = await HttpClient().getUrl(Uri.parse(
'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
final response = await request.close();
List<List<dynamic>> rowsAsListOfValues;
await for (final csvString in response.transform(const Utf8Decoder())) {
rowsAsListOfValues = const CsvToListConverter().convert(csvString);
}
return rowsAsListOfValues;
}
class _AppState extends State<HomePage> {
List<List<dynamic>> rowsAsListOfValues;
ScrollController _controller;
#override
void didChangeDependencies() async {
super.didChangeDependencies();
rowsAsListOfValues = await fetchUserData();
super.setState(() {}); // to update widget data
}
#override
void initState() {
super.initState();
_controller = ScrollController();
_controller = new ScrollController()..addListener(_scrollListener);
}
void _scrollListener() {
if (_controller.position.extentAfter <= 0.0 &&
_controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange) {
print("call fetch method again");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
rowsAsListOfValues == null
? Text("Loading data...")
: Text(
'', // $rowsAsListOfValues
),
rowsAsListOfValues == null
? CircularProgressIndicator()
: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'City',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Branches',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: List.generate(rowsAsListOfValues.length - 1, (index) {
return DataRow(
cells: <DataCell>[
// DataCell(Text('${rowsAsListOfValues[index + 1][0]}')), // Index
DataCell(Text('${rowsAsListOfValues[index + 1][1]}')), // city
DataCell(Text('${rowsAsListOfValues[index + 1][2]}')), // branch
],
);
})),
],
),
),
);
}
}
My dat astructure is:
I found it using onSelectChanged as below:
showCheckboxColumn: false, // <-- this is important
and
rows: List.generate(rowsAsListOfValues.length - 1, (index) {
return DataRow(
onSelectChanged: (bool selected) {
if (selected) {
print('index-selected: ${rowsAsListOfValues[index + 1][0]}');
}
},
cells: <DataCell>[
// DataCell(Text('${rowsAsListOfValues[index + 1][0]}')), // Index
DataCell(Text('${rowsAsListOfValues[index + 1][1]}')), // city
DataCell(Text('${rowsAsListOfValues[index + 1][2]}')), // branch
],
);
}),
And the updated code is:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:csv/csv.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(title: 'Flutter Demo Home Page'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_AppState createState() => _AppState();
}
Future<List<List<dynamic>>> fetchUserData() async {
final request = await HttpClient().getUrl(Uri.parse(
'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
final response = await request.close();
List<List<dynamic>> rowsAsListOfValues;
await for (final csvString in response.transform(const Utf8Decoder())) {
rowsAsListOfValues = const CsvToListConverter().convert(csvString);
}
return rowsAsListOfValues;
}
class _AppState extends State<HomePage> {
List<List<dynamic>> rowsAsListOfValues;
// ScrollController _controller;
#override
void didChangeDependencies() async {
super.didChangeDependencies();
rowsAsListOfValues = await fetchUserData();
super.setState(() {}); // to update widget data
}
#override
void initState() {
super.initState();
// _controller = ScrollController();
// _controller = new ScrollController()..addListener(_scrollListener);
}
/*
void _scrollListener() {
if (_controller.position.extentAfter <= 0.0 &&
_controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange) {
print("call fetch method again");
}
} */
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
rowsAsListOfValues == null
? Text("Loading data...")
: Text(
'', // $rowsAsListOfValues
),
rowsAsListOfValues == null
? CircularProgressIndicator()
: DataTable(
showCheckboxColumn: false, // <-- this is important
columns: const <DataColumn>[
DataColumn(
label: Text(
'City',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Branches',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: List.generate(rowsAsListOfValues.length - 1, (index) {
return DataRow(
onSelectChanged: (bool selected) {
if (selected) {
print('index-selected: ${rowsAsListOfValues[index + 1][0]}');
}
},
cells: <DataCell>[
// DataCell(Text('${rowsAsListOfValues[index + 1][0]}')), // Index
DataCell(Text('${rowsAsListOfValues[index + 1][1]}')), // city
DataCell(Text('${rowsAsListOfValues[index + 1][2]}')), // branch
],
);
}),
),
],
),
),
);
}
}

Displaying data in a table at Widget

I've the below code, that fetch data from url, and display it in the Widget, this is a csv data, how can I dislay it as a table?
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:csv/csv.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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();
}
Future<List<List<dynamic>>> fetchUserData() async {
final request = await HttpClient().getUrl(Uri.parse(
'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
final response = await request.close();
List<List<dynamic>> rowsAsListOfValues;
await for (final csvString in response.transform(const Utf8Decoder())) {
rowsAsListOfValues =
const CsvToListConverter().convert(csvString);
}
// print(rowsAsListOfValues);
return rowsAsListOfValues;
}
class _MyHomePageState extends State<MyHomePage> {
var rowsAsListOfValues;
#override
void initState() {
super.initState();
rowsAsListOfValues = "Loading data...";
}
#override
void didChangeDependencies() async {
super.didChangeDependencies();
rowsAsListOfValues = await fetchUserData();
super.setState(() {}); // to update widget data
print(rowsAsListOfValues);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$rowsAsListOfValues',
),
],
),
),
);
}
}
I know there is DataTable widget, but do not know how to connect it with Dynamic data.
With static data, the code will be like:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:csv/csv.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(title: 'Flutter Demo Home Page'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_AppState createState() => _AppState();
}
Future<List<List<dynamic>>> fetchUserData() async {
final request = await HttpClient().getUrl(Uri.parse(
'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
final response = await request.close();
List<List<dynamic>> rowsAsListOfValues;
await for (final csvString in response.transform(const Utf8Decoder())) {
rowsAsListOfValues =
const CsvToListConverter().convert(csvString);
}
return rowsAsListOfValues;
}
class _AppState extends State<HomePage> {
var rowsAsListOfValues;
#override
void didChangeDependencies() async {
super.didChangeDependencies();
rowsAsListOfValues = await fetchUserData();
super.setState(() {}); // to update widget data
/// new
print(rowsAsListOfValues);
}
#override
void initState() {
super.initState();
rowsAsListOfValues = "Loading data...";
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$rowsAsListOfValues',
),
DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'City',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Branches',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Dammam')),
DataCell(Text('2')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Khobar')),
DataCell(Text('3')),
],
),
],
),
],
),
),
);
}
}
You can copy paste run full code below
You can use List.generate(rowsAsListOfValues.length - 1 to avoid header
code snippet
List<List<dynamic>> rowsAsListOfValues;
...
rowsAsListOfValues == null
? CircularProgressIndicator()
: DataTable(
...
rows: List.generate(rowsAsListOfValues.length - 1, (index) {
return DataRow(
cells: <DataCell>[
DataCell(Text('${rowsAsListOfValues[index + 1][0]}')),
DataCell(Text('${rowsAsListOfValues[index + 1][1]}')),
],
);
})),
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:csv/csv.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(title: 'Flutter Demo Home Page'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_AppState createState() => _AppState();
}
Future<List<List<dynamic>>> fetchUserData() async {
final request = await HttpClient().getUrl(Uri.parse(
'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
final response = await request.close();
List<List<dynamic>> rowsAsListOfValues;
await for (final csvString in response.transform(const Utf8Decoder())) {
rowsAsListOfValues = const CsvToListConverter().convert(csvString);
}
return rowsAsListOfValues;
}
class _AppState extends State<HomePage> {
List<List<dynamic>> rowsAsListOfValues;
#override
void didChangeDependencies() async {
super.didChangeDependencies();
rowsAsListOfValues = await fetchUserData();
super.setState(() {}); // to update widget data
/// new
print(rowsAsListOfValues);
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
rowsAsListOfValues == null
? Text("Loading data...")
: Text(
'$rowsAsListOfValues',
),
rowsAsListOfValues == null
? CircularProgressIndicator()
: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'City',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Branches',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: List.generate(rowsAsListOfValues.length - 1, (index) {
return DataRow(
cells: <DataCell>[
DataCell(Text('${rowsAsListOfValues[index + 1][0]}')),
DataCell(Text('${rowsAsListOfValues[index + 1][1]}')),
],
);
})),
],
),
),
);
}
}
You can use a Table widget like this:
List<List<dynamic>> rowsAsListOfValues;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Table(
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(200.0),
},
border: TableBorder.all(width: 1.0),
children: rowsAsListOfValues.map((item) {
return TableRow(
children: item.map((row) {
return Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
row.toString(),
style: TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}

How can I make the initial value of a TextFormField equal to a variable loaded from shared preferences? (Flutter)

I want to make the initial value of the TextFormField equal to the counter variable. The counter is maintained between app restarts, but when I restart the app, the initial value of the text field is always 0.
Is there a better way of doing that?
(I'm new to programming, sorry if it's a dumb question)
Here's the code I used.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shared preferences demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Shared preferences demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {
super.initState();
_loadCounter();
}
//Loading counter value on start
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0);
});
}
//Incrementing counter after click
_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
TextFormField(
initialValue: '$_counter',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Try adding a controller for TextFormField and update the value after getting it from SharedPreferences.
Something like this.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shared preferences demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Shared preferences demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
int _counter = 0;
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
_loadCounter();
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0);
myController.text = _counter.toString();
});
}
_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
myController.text = _counter.toString();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
TextFormField(
controller: myController,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Hope this solves your issue.

How to make a counter that multiples in the background with async

I'm trying to make a clicker-like app to test myself. Everything was perfect until I came to async thing. The thing I want to do is a program that multiplies itself by it's house numbers. Like, user if user has 2 home, user should earn 2 points per second. I read the original documentation of dart and made it from copying there.
Code:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:async/async.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Zikirmatik'),
);
}
}
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 = 0;
int _max = 0;
int _ev = 0;
int _toplanan = 0;
void _incrementCounter() {// Eklemeler sürekli tekrar çağrıldığı için bunları ayrı bir voide almamız gerek
setState(() { //Tekrar çağrılmasını sağlayan komut
_counter++;
});
}
void _decreaseCounter(){
setState(() {
_counter--;
});
}
void _resetCounter(){
setState(() {
_counter = 0;
});
}
void _evArttiran(){
setState(() {
_ev++;
});
}
void _otoArttiran(){
setState(() {
_toplanan = _ev * 1;
});
}
#override
Widget build(BuildContext context) {
if(_counter > _max){ //Yüksek skor if'i
_max = _counter;
}
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Skor:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1, // Anlık skoru kalın göstern
),
Text(
'Yüksek Skor:',
),
Text(
'$_max',
),
Text(
'Ev Sayısı:',
),
Text(
'$_ev',
),
OutlineButton( // Büyük button
onPressed: () => _incrementCounter(), // Ayrı bi void yazmamak için fat işaret kullanıyoruz
child: Container(
width: 1000, // Ayarlamazsanız küçük oluyor
height: 500,
child: Icon(Icons.add, size:100)
)
)
],
),
),
floatingActionButton: Row( //Yan yana düğme yazmak için Row gerek
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton( //Düz ufak butonlar
onPressed: _evArttiran,
child: Icon(Icons.home),
),
],
)
);
}
main() async{
Timer(Duration(seconds: 1), () {
_otoArttiran;
debugPrint(_toplanan.toString());
_counter += _toplanan;
});
}
}
You need to create a periodic timer and don't forget to put () after _otoArttiran inside the timer callback:
main() async{
Timer.periodic(Duration(seconds: 1), (_) {
_otoArttiran();
debugPrint(_toplanan.toString());
_counter += _toplanan;
});
}
You need to call this function in order for the timer to start working, so let's add initState method to your _MyHomePageState:
#override void initState() {
super.initState();
main();
}
Done!
So here is the complete code:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(new TheApp());
class TheApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Zikirmatik'),
);
}
}
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 = 0;
int _max = 0;
int _ev = 0;
int _toplanan = 0;
#override void initState() {
super.initState();
main();
}
void _incrementCounter() {// Eklemeler sürekli tekrar çağrıldığı için bunları ayrı bir voide almamız gerek
setState(() { //Tekrar çağrılmasını sağlayan komut
_counter++;
});
}
void _decreaseCounter(){
setState(() {
_counter--;
});
}
void _resetCounter(){
setState(() {
_counter = 0;
});
}
void _evArttiran(){
setState(() {
_ev++;
});
}
void _otoArttiran(){
setState(() {
_toplanan = _ev * 1;
});
}
#override
Widget build(BuildContext context) {
if(_counter > _max){ //Yüksek skor if'i
_max = _counter;
}
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Skor:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1, // Anlık skoru kalın göstern
),
Text(
'Yüksek Skor:',
),
Text(
'$_max',
),
Text(
'Ev Sayısı:',
),
Text(
'$_ev',
),
OutlineButton( // Büyük button
onPressed: () => _incrementCounter(), // Ayrı bi void yazmamak için fat işaret kullanıyoruz
child: Container(
width: 1000, // Ayarlamazsanız küçük oluyor
height: 500,
child: Icon(Icons.add, size:100)
)
)
],
),
),
floatingActionButton: Row( //Yan yana düğme yazmak için Row gerek
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton( //Düz ufak butonlar
onPressed: _evArttiran,
child: Icon(Icons.home),
),
],
)
);
}
main() async{
Timer.periodic(Duration(seconds: 1), (_) {
_otoArttiran();
debugPrint(_toplanan.toString());
_counter += _toplanan;
});
}
}
I'm not sure if i understood correctly but maybe you can to try something like this:
(inside _MyHomePageState)
#override
void initState() {
super.initState();
Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_counter = _counter + _ev;
});
});
}