Flutter the values in the array all become the same - arrays

Please understand that I am not good at English because I am a foreigner.
There was a problem while I was programming.
I was going to put each object in the array. We succeeded in putting the object in. But there was a problem with all the objects in the array being the same.
I want to solve this problem.
I'd appreciate it if you could help me.
Main.dart :
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'Page/FirstPage.dart';
import 'Page/FourPage.dart';
import 'Page/SecondPage.dart';
import 'Page/ThirdPage.dart';
import 'module/goal.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Index()),
ChangeNotifierProvider(create: (_) => Goal('None')),
ChangeNotifierProvider(create: (_) => GoalList())
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Todo App',
home: MainPage(),
),
);
}
}
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
var currentTab = [FirstPage(), SecondPage(), ThirdPage(), FourPage()];
#override
Widget build(BuildContext context) {
Index currentIndex = Provider.of<Index>(context);
Goal goal = Provider.of<Goal>(context);
return Scaffold(
body: IndexedStack(
index: currentIndex.currentIndex,
children: currentTab,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: currentIndex.currentIndex,
onTap: (index) {
currentIndex.currentIndex = index;
},
type: BottomNavigationBarType.fixed,
// 하단바 아이콘 고정
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.add_circle), title: Text('Todo Create')),
BottomNavigationBarItem(
icon: Icon(Icons.format_list_bulleted),
title: Text('Todo List')),
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today), title: Text('none')),
BottomNavigationBarItem(
icon: Icon(Icons.settings), title: Text('none')),
],
selectedItemColor: Colors.black87,
// 선택된 index 색깔
unselectedItemColor: Colors.black54,
// 선택안된 index 색깔
),
);
}
}
Goal.dart
import 'package:flutter/cupertino.dart';
// 아이콘 설정 , 제목 , 기간 ,
class Goal with ChangeNotifier {
String _name;
String get getName => _name;
set setName(String name)=> _name = name;
Goal(this._name);
#override String toString() => _name;
}
class Index with ChangeNotifier {
int _currentIndex = 0;
get currentIndex => _currentIndex;
set currentIndex(int index) {
_currentIndex = index;
notifyListeners();
}
}
class GoalList with ChangeNotifier {
List<Goal> goalList = [];
Goal getGoal;
addGoalInList() {
goalList.add(getGoal);
notifyListeners();
}
}
FirstPage.dart
import 'package:flutter/material.dart';
import 'package:goalapp/module/goal.dart';
import 'package:provider/provider.dart';
class FirstPage extends StatefulWidget {
#override
_FirstPageState createState() => _FirstPageState();
}
// 객체를 만들 클래스를 생성
// 생성된 객체를 내부저장소에 저장
class _FirstPageState extends State<FirstPage> {
final _formKey = GlobalKey<FormState>();
TextEditingController _names = TextEditingController();
#override
void dispose() {
_names.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
Index currentIndex = Provider.of<Index>(context);
Goal goal = Provider.of<Goal>(context);
GoalList goalList = Provider.of<GoalList>(context);
return Scaffold(
appBar: AppBar(
title: Text('Todo add'),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
children: <Widget>[
Container(
width: 200,
height: 200,
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
controller: _names,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(10))),
filled: true,
hintText: 'Todo Name'),
),
],
),
),
),
RaisedButton(
onPressed: () {
goal.setName = _names.text;
goalList.getGoal = goal;
goalList.addGoalInList();
currentIndex.currentIndex = 1;
},
child: Text('Create'),
)
],
)
],
),
);
}
}
SecondPage.dart
import 'package:flutter/material.dart';
import 'package:goalapp/module/goal.dart';
import 'package:provider/provider.dart';
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
Goal goal = Provider.of<Goal>(context);
GoalList goalList = Provider.of<GoalList>(context);
return Scaffold(
appBar: AppBar(
title: Text('Todo ListView'),
),
body: Column(
children: <Widget>[
Expanded(
child: Consumer<GoalList>(builder: (context, goal, child) {
return ListView.separated(
itemCount: goal.goalList.length,
itemBuilder: (context, index) {
return Container(
child: ListTile(
title: Text(goalList.goalList[index].getName),
subtitle: Text('2020.07.16 ~ 2020.08.16'),
),
);
},
separatorBuilder: (context, index) {
return Divider();
},
);
}),
),
RaisedButton(
onPressed: () {
print(goalList.goalList[0]);
},
child: Text('List[0]'),
),
RaisedButton(
onPressed: () {
print(goalList.goalList[1]);
},
child: Text('List[1]'),
),
],
));
}
}

You can copy paste run full code below
Step 1: Change GoalList's addGoalInList(Goal goal)
class GoalList with ChangeNotifier {
List<Goal> goalList = [];
Goal getGoal;
addGoalInList(Goal goal) {
goalList.add(goal);
notifyListeners();
}
}
Step 2: You do not need Goal goal = Provider.of<Goal>(context);
#override
Widget build(BuildContext context) {
Index currentIndex = Provider.of<Index>(context);
// Goal goal = Provider.of<Goal>(context);
Step 3: Add goal with Goal goal = Goal(_names.text); then goalList.addGoalInList(goal);
RaisedButton(
onPressed: () {
Goal goal = Goal(_names.text);
//goal.setName = _names.text;
//goalList.getGoal = goal;
goalList.addGoalInList(goal);
currentIndex.currentIndex = 1;
},
child: Text('Create'),
)
working demo
full code
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter/cupertino.dart';
// 아이콘 설정 , 제목 , 기간 ,
class Goal with ChangeNotifier {
String _name;
String get getName => _name;
set setName(String name)=> _name = name;
Goal(this._name);
#override String toString() => _name;
}
class Index with ChangeNotifier {
int _currentIndex = 0;
get currentIndex => _currentIndex;
set currentIndex(int index) {
_currentIndex = index;
notifyListeners();
}
}
class GoalList with ChangeNotifier {
List<Goal> goalList = [];
Goal getGoal;
addGoalInList(Goal goal) {
goalList.add(goal);
notifyListeners();
}
}
class FirstPage extends StatefulWidget {
#override
_FirstPageState createState() => _FirstPageState();
}
// 객체를 만들 클래스를 생성
// 생성된 객체를 내부저장소에 저장
class _FirstPageState extends State<FirstPage> {
final _formKey = GlobalKey<FormState>();
TextEditingController _names = TextEditingController();
#override
void dispose() {
_names.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
Index currentIndex = Provider.of<Index>(context);
// Goal goal = Provider.of<Goal>(context);
GoalList goalList = Provider.of<GoalList>(context);
return Scaffold(
appBar: AppBar(
title: Text('Todo add'),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
children: <Widget>[
Container(
width: 200,
height: 200,
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
controller: _names,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(10))),
filled: true,
hintText: 'Todo Name'),
),
],
),
),
),
RaisedButton(
onPressed: () {
Goal goal = Goal(_names.text);
//goal.setName = _names.text;
//goalList.getGoal = goal;
goalList.addGoalInList(goal);
currentIndex.currentIndex = 1;
},
child: Text('Create'),
)
],
)
],
),
);
}
}
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
Goal goal = Provider.of<Goal>(context);
GoalList goalList = Provider.of<GoalList>(context);
return Scaffold(
appBar: AppBar(
title: Text('Todo ListView'),
),
body: Column(
children: <Widget>[
Expanded(
child: Consumer<GoalList>(builder: (context, goal, child) {
return ListView.separated(
itemCount: goal.goalList.length,
itemBuilder: (context, index) {
return Container(
child: ListTile(
title: Text(goalList.goalList[index].getName),
subtitle: Text('2020.07.16 ~ 2020.08.16'),
),
);
},
separatorBuilder: (context, index) {
return Divider();
},
);
}),
),
RaisedButton(
onPressed: () {
print(goalList.goalList[0]);
},
child: Text('List[0]'),
),
RaisedButton(
onPressed: () {
print(goalList.goalList[1]);
},
child: Text('List[1]'),
),
],
));
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Index()),
ChangeNotifierProvider(create: (_) => Goal('None')),
ChangeNotifierProvider(create: (_) => GoalList())
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Todo App',
home: MainPage(),
),
);
}
}
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
var currentTab = [FirstPage(), SecondPage()];
#override
Widget build(BuildContext context) {
Index currentIndex = Provider.of<Index>(context);
Goal goal = Provider.of<Goal>(context);
return Scaffold(
body: IndexedStack(
index: currentIndex.currentIndex,
children: currentTab,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: currentIndex.currentIndex,
onTap: (index) {
currentIndex.currentIndex = index;
},
type: BottomNavigationBarType.fixed,
// 하단바 아이콘 고정
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.add_circle), title: Text('Todo Create')),
BottomNavigationBarItem(
icon: Icon(Icons.format_list_bulleted),
title: Text('Todo List')),
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today), title: Text('none')),
BottomNavigationBarItem(
icon: Icon(Icons.settings), title: Text('none')),
],
selectedItemColor: Colors.black87,
// 선택된 index 색깔
unselectedItemColor: Colors.black54,
// 선택안된 index 색깔
),
);
}
}

Related

Same date is displaying for all the notes in flutter. Date is not updating dynamically

I am a beginner in flutter and I am building a simple note-taking app. Whenever a user creates a note, the date month, and year of creation will get inserted into SQflite DB and I am fetching the same on the main screen. But for all other notes also same date month and year are displaying. I don't know where it went wrong, any help here, please. I am stuck in this for the past 2 days. I have checked other answers in StackOverflow, from there I learnt the implementation of date, but couldn't resolve this problem.
Database Helper Class
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'model_notes.dart';
class DatabaseHelper {
static final _databaseName = "myNote.db";
static final _databaseVersion = 1;
static final table = 'notes_table';
static final columnId = 'id';
static final columnTitle = 'title';
static final columnBody = 'body';
static final columnDate = 'date';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await initDatabase();
return _database;
}
initDatabase() async {
String path = join(await getDatabasesPath(), _databaseName);
return await openDatabase(path,
version: _databaseVersion, onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnTitle TEXT NOT NULL,
$columnBody TEXT NOT NULL,
$columnDate TEXT NOT NULL
)
''');
}
Future<int> insert(Note note) async {
Database db = await instance.database;
if (note.title.trim().isEmpty) note.title = 'Untitled Note';
return await db.insert(table, {'title': note.title, 'body': note.body, 'date': note.date});
}
Future<List<Note>> getNotesFromDB() async {
final db = await database;
List<Note> notesList = [];
List<Map> maps = await db.query(table);
if (maps.length > 0) {
maps.forEach((map) {
notesList.add(Note.fromMap(map));
});
}
return notesList;
}
}
This is my note model class
import 'db_operations.dart';
class Note {
int id;
String title;
String body;
String date;
Note(this.id, this.title, this.body, this.date);
Note.fromMap(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
body = map['body'];
date = map['date'];
}
Map<String, dynamic> toMap() {
return {
DatabaseHelper.columnId: id,
DatabaseHelper.columnTitle: title,
DatabaseHelper.columnBody: body,
DatabaseHelper.columnDate: date,
};
}
#override
String toString() {
return '$title, $date';
}
}
This is where I am adding Notes
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:note_taking_app/constants/buttons_and_icons_misc(classes).dart';
import 'package:note_taking_app/db/db_operations.dart';
import 'package:note_taking_app/db/model_notes.dart';
final bodyController = TextEditingController();
final headerController = TextEditingController();
final dbHelper = DatabaseHelper.instance;
String formattedDate = DateFormat.yMMMd('en_US').format(DateTime.now());
class AddingNotes extends StatefulWidget {
#override
_AddingNotesState createState() => _AddingNotesState();
}
class _AddingNotesState extends State<AddingNotes> {
#override
void initState() {
super.initState();
bodyController.clear();
headerController.clear();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backwardsCompatibility: true,
leading: LeadingIcon(
callBack: () {
Navigator.pop(context);
},
),
backgroundColor: Colors.white.withOpacity(0.4),
actions: <Widget>[
ActionsIconButton(
icon: Icon(undo, color: black),
callBack: () {
debugPrint('undo tapped');
},
),
ActionsIconButton(
icon: Icon(redo, color: black),
callBack: () {
debugPrint('redo tapped');
},
),
ActionsIconButton(
icon: Icon(save, color: black),
callBack: () async {
String title = headerController.text;
String body = bodyController.text;
Note note = Note(20, title, body, formattedDate);
var value = await dbHelper.insert(note);
Navigator.pop(context);
},
)
],
),
body: Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
HeaderBody(
textEditingController: headerController,
),
SizedBox(
height: 32.0,
),
Expanded(
child: NotesBody(
textEditingController: bodyController,
),
),
],
),
),
),
);
}
}
This is where I am displaying notes
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:note_taking_app/constants/buttons_and_icons_misc(classes).dart';
import 'package:note_taking_app/constants/text_and_decorations(methods).dart';
import 'package:note_taking_app/db/model_notes.dart';
import 'package:note_taking_app/ui/adding_notes.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
List<Note> noteList = [];
#override
void initState() {
super.initState();
dbHelper.initDatabase();
setNotesFromDB();
}
setNotesFromDB() async {
print("Entered setNotes in main page");
var fetchedNotes = await dbHelper.getNotesFromDB();
setState(() {
noteList = fetchedNotes;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: mainScreenAppBar,
floatingActionButton: FAB(
whatToDo: () {
gotoAddingNotesPage(context);
},
),
body: SafeArea(
child: ListView.builder(
itemCount: noteList.length,
itemBuilder: (context, index) {
return TileCard(
titleText: ('${noteList[index].title}'),
dateText: ('${noteList[index].date}'),
);
},
),
),
);
}
gotoAddingNotesPage(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddingNotes()),
).then((value) => setState(() {
setNotesFromDB();
}));
}
}
This is my TileCard class where I've declared dateText widget
class TileCard extends StatelessWidget {
final String titleText;
final String dateText;
const TileCard({#required this.titleText, #required this.dateText});
#override
Widget build(BuildContext context) {
return Container(
height: 90,
child: Card(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),
elevation: 0,
margin: const EdgeInsets.all(8.0),
child: ListTile(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),
title: Text(
titleText,
style: TextStyle(fontWeight: FontWeight.w700),
),
tileColor: Colors.grey.withOpacity(0.2),
subtitle: Padding(
padding: EdgeInsets.only(top: 10.0),
child: Text(dateText),
),
),
),
);
}
}
I have added image, this is how it looks now.

I am creating note app in flutter and stuck in sqflite, how can I pass my title and body to insert method

I am building a simple note app, but I am stuck at saving the data (title and body) using SQLite.
DataBaseHelper class
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'model_notes.dart';
class DatabaseHelper {
static final _databaseName = "myNote.db";
static final _databaseVersion = 1;
static final table = 'notes_table';
static final columnId = 'id';
static final columnTitle = 'title';
static final columnBody = 'body';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}
_initDatabase() async {
String path = join(await getDatabasesPath(), _databaseName);
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnTitle TEXT NOT NULL,
$columnBody TEXT NOT NULL
)
''');
}
Future<int> insert(Note note) async {
Database db = await instance.database;
return await db.insert(table, {'title': note.title, 'body': note.body});
}
This is the Model Class for Notes
import 'db_operations.dart';
class Note {
int id;
String title;
String body;
Note(this.id, this.title, this.body);
Note.fromMap(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
body = map['body'];
}
Map<String, dynamic> toMap(){
return {
DatabaseHelper.columnId : id,
DatabaseHelper.columnTitle : title,
DatabaseHelper.columnBody : body
};
}
}
and this is where I'm calling insert method (class name = adding_notes.dart)
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:note_taking_app/constants/buttons_and_icons_misc(classes).dart';
import 'package:note_taking_app/db/db_operations.dart';
import 'package:note_taking_app/db/model_notes.dart';
import 'package:sqflite/sqflite.dart';
import 'main_screen.dart';
final bodyController = TextEditingController();
final headerController = TextEditingController();
final dbHelper = DatabaseHelper.instance;
class AddingNotes extends StatefulWidget {
#override
_AddingNotesState createState() => _AddingNotesState();
}
class _AddingNotesState extends State<AddingNotes> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backwardsCompatibility: true,
leading: LeadingIcon(
callBack: () {
Navigator.pop(context);
},
),
backgroundColor: Colors.white.withOpacity(0.4),
actions: <Widget>[
ActionsIconButton(
icon: Icon(undo, color: black),
callBack: () {
debugPrint('undo tapped');
},
),
ActionsIconButton(
icon: Icon(redo, color: black),
callBack: () {
debugPrint('redo tapped');
},
),
ActionsIconButton(
icon: Icon(save, color: black),
callBack: () async {
debugPrint(bodyController.text);
debugPrint(headerController.text);
getHeaderDataToMainScreen(context);
String title = headerController.text;
String body = bodyController.text;
/*This is where I am calling insert method*/
dbHelper.insert(title, body);
},
)
],
),
body: Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
HeaderBody(
textEditingController: headerController,
),
SizedBox(
height: 32.0,
),
Expanded(
child: NotesBody(
textEditingController: bodyController,
),
),
],
),
),
),
);
}
}
getHeaderDataToMainScreen(BuildContext context){
Navigator.push(context,
MaterialPageRoute(
builder: (context) => MainScreen(
heading : headerController.text,
)
)
);
}
It is showing too many positional arguments expected 1 found 2. I know I need to send 1 argument, but how can I send both title and body as 1 argument. Maybe through List I can send it but I don't know how to do that. Any help here guys, I'm stuck at this for the past 5 days.
Check the example below that i have created based on the code you provided.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'db_operations.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: AddingNotes(),
));
}
final bodyController = TextEditingController();
final headerController = TextEditingController();
final dbHelper = DatabaseHelper.instance;
class AddingNotes extends StatefulWidget {
#override
_AddingNotesState createState() => _AddingNotesState();
}
class _AddingNotesState extends State<AddingNotes> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
Icons.add,
color: Colors.black,
),
),
),
backgroundColor: Colors.white.withOpacity(0.4),
actions: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
debugPrint('undo tapped');
},
child: Icon(
Icons.undo,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
debugPrint('redo tapped');
},
child: Icon(
Icons.redo,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () async {
debugPrint(bodyController.text);
debugPrint(headerController.text);
//getHeaderDataToMainScreen(context);
String title = headerController.text;
String body = bodyController.text;
Note note = Note(20, title, body);
var value = await dbHelper.insert(note);
print("if 1 is return then insert success and 0 then not inserted : $value");
},
child: Icon(
Icons.save,
color: Colors.black,
),
),
)
],
),
body: Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
TextField(
controller: headerController,
),
SizedBox(
height: 32.0,
),
Expanded(
child: TextField(
controller: bodyController,
),
),
],
),
),
),
);
}
}
// getHeaderDataToMainScreen(BuildContext context) {
// Navigator.push(context,
// MaterialPageRoute(
// builder: (context) =>
// MainScreen(
// heading: headerController.text,
// )
// )
// );
// }
class Note {
int id;
String title;
String body;
Note(this.id, this.title, this.body);
Note.fromMap(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
body = map['body'];
}
Map<String, dynamic> toMap() {
return {
DatabaseHelper.columnId: id,
DatabaseHelper.columnTitle: title,
DatabaseHelper.columnBody: body
};
}
}
This is just a sample demo example added every thing in one file and made many changes. change it as per your needs.
You don't need a auto increment id as you have given it in the database. Run the app and let me know if it works.

Compare two lists with String data?

How I can compare two lists with String data?
I need if values in second list match with first, change icon to red, if not match to green.
isEqual ? Colors.red : Colors.green
First list
List<String> pcAll = ['S01', 'S02', 'S03', 'S04', 'S05'];
Second list
List<String> pcBusy = ['S02', 'S03'];
class ComputerGrid extends StatelessWidget {
const ComputerGrid();
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 6 / 3,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
),
itemCount: pcAll.length,
itemBuilder: (BuildContext context, index) {
return GridTile(
child: Container(
color: isEqual() ? Colors.red : Colors.green,
child: Center(
child: Text(
pcAll[index],
),
class _EvrokoStandartScreenState extends State<EvrokoStandartScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
'ЕВРОКО Стандарт',
),
),
body: ComputerGrid(),
#Чак-Джонс you can compare the list as below.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> pcAll = ['S01', 'S02', 'S03', 'S04', 'S05'];
List<String> pcBusy = ['S02', 'S03'];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: GridView.builder(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 6 / 3,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
),
itemCount: pcAll.length,
itemBuilder: (BuildContext context, index) {
return GridTile(
child: Container(
color: pcBusy.contains(pcAll[index]) ? Colors.red : Colors.green,
child: Center(
child: Text(pcAll[index]),
),
),
);
},
),
);
}
}
You can compare two lists in flutter using listEquals method, or create a custom method like this.
bool areListsEqual(var list1, var list2) {
// check if both are lists
if(!(list1 is List && list2 is List)
// check if both have same length
|| list1.length!=list2.length) {
return false;
}
// check if elements are equal
for(int i=0;i<list1.length;i++) {
if(list1[i]!=list2[i]) {
return false;
}
}
return true;
}
void main(){
List list1 = [24, 'Hello', 84];
List list2 = [24, 'Hello', 84];
List list3 = [11, 'Hi', 41];
if(areListsEqual(list1, list2)) {
print('list1 and list2 are equal in value.');
} else {
print('list1 and list2 are not equal in value.');
}
if(areListsEqual(list1, list3)) {
print('list1 and list3 are equal in value.');
} else {
print('list1 and list3 are not equal in value.');
}
}
For listEqual
import 'package:flutter/foundation.dart';
...............
bool isEqual = listEquals(pcAll, pcBusy);
For DeepCollectionEquality
import 'package:collection/collection.dart';
.......
Function deepEq = const DeepCollectionEquality().equals;
bool idDeepEqual = deepEq(pcAll, pcBusy);
Normal hardCoded
List<String> pcAll = [
'S01',
'S02',
'S03',
'S04',
'S05',
'S06',
'S07',
'S09',
'S10'
];
List<String> pcBusy = ['S02', 'S03', 'S05', 'S06', 'S07', 'S08'];
List<String> resultSet1 = [];
pcBusy.forEach((pc) {
if (pcAll.contains(pc)) resultSet1.add(pc);
});
print(resultSet1);
print(resultSet1.length > 0 ? "didnot match" : "match");

Flutter textformfield auto de-focus

This is the function I'm using to get a form displayed on my screen.
Form getNewLoanForm() {
return new Form(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(labelText: 'Loan name'),
validator: (value) {
if (value.isEmpty) {
return 'Enter name';
} else {
return null;
}
},
onSaved: (value) => _loanName = value,
),
new Container(height: 16.0),
new RaisedButton(
child: new Text(
'ADD',
style: new TextStyle(color: Colors.white, fontSize: 17.0),
),
onPressed: addNewLoan,
color: Colors.blue,
)
],
),
);
}
Everything works fine up unit now. The problem starts when I add
final formKey = new GlobalKey<FormState>();
I declare this varial in class level. and use it in form.
return new Form(
key: formKey,
Like this and now the TextFormField starts to behave weirdly. Now if I select the text field it deselects itself.
Now keep in mind that this doesn't happen if I make this page my root page. But I'm pushing this page from my root page. If I make this page my root page the problem doesn't occur there.
Any idea what's wrong here?
Okay I'm putting my whole class
import 'package:flutter/material.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
import 'package:intl/intl.dart';
class NewLoan extends StatelessWidget {
String _loanName;
String _dateCreated;
final formKey = new GlobalKey<FormState>();
void addNewLoan() {}
Form getNewLoanForm(BuildContext context) {
final dateFormat = DateFormat("dd/MM/yyyy");
return new Form(
// key: formKey,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(labelText: 'Loan name'),
validator: (value) {
if (value.isEmpty) {
return 'Enter name';
} else {
_loanName = value;
return null;
}
},
),
new Container(height: 16.0),
DateTimePickerFormField(
decoration: new InputDecoration(labelText: 'Date'),
format: dateFormat,
dateOnly: true,
onChanged: (date) {
print('Selected date ${date.toString()}');
Scaffold
.of(context)
.showSnackBar(SnackBar(content: Text('$date')));
},
),
new Container(height: 16.0),
new RaisedButton(
child: new Text(
'ADD',
style: new TextStyle(color: Colors.white, fontSize: 17.0),
),
onPressed: addNewLoan,
color: Colors.blue,
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text('New Loan'),
),
body: new Container(
padding: new EdgeInsets.all(20.0),
child: getNewLoanForm(context),
),
);
}
}
My Root page
import 'dart:async';
import 'package:firebase/new_loan.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'auth.dart';
import 'current_balance_page.dart';
import 'dart:io' show Platform;
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
class HomePage extends StatefulWidget {
HomePage({this.auth, this.onSignOut});
final BaseAuth auth;
final VoidCallback onSignOut;
#override
_HomePageState createState() => _HomePageState();
}
FirebaseApp app;
Future<FirebaseApp> firebaseApp() async {
final FirebaseApp app = await FirebaseApp.configure(
name: 'hisab-442a2',
options: Platform.isIOS
? const FirebaseOptions(
googleAppID: '1:18726312:ios:1b7829f2ac180d28',
gcmSenderID: '75461431231231291692',
databaseURL: 'https://hisab-44s2a2.firebaseio.com',
)
: const FirebaseOptions(
googleAppID: '1:297855924061:android:669871c998cc21bd',
apiKey: 'AIzaSyD_shO5mfO9lhy2TVWhfo1VUmARKlG4suk',
databaseURL: 'https://hisab-442a2.firebaseio.com',
),
);
return app;
}
enum Balancestatus { checking, found, noBalance }
class _HomePageState extends State<HomePage> {
Balancestatus status = Balancestatus.checking;
DatabaseReference _databaseRef;
#override
void initState() {
super.initState();
getDatabaseRef();
}
void getDatabaseRef() async {
app = await firebaseApp();
final FirebaseDatabase database = new FirebaseDatabase(app: app);
_databaseRef = database.reference();
_databaseRef.child('ccurrent_balance').once().then((DataSnapshot snapshot) {
print('Current balance ${snapshot.value}');
int balance = snapshot.value;
setState(() {
if (balance == null || balance == 0) {
status = Balancestatus.noBalance;
} else {
status = Balancestatus.found;
}
});
});
}
Future _signOut() async {
try {
await widget.auth.singOut();
widget.onSignOut();
} catch (e) {
print('Error signing out: $e');
}
}
void balanceSet() {
setState(() {
status = Balancestatus.checking;
});
}
#override
Widget build(BuildContext context) {
switch (status) {
case Balancestatus.checking:
return new WelcomePage(onSignOut: _signOut);
case Balancestatus.found:
// return new NewLoan();
return new LoanList(onSignOut: _signOut);
case Balancestatus.noBalance:
return CurrentBalancePage(
databaseRef: _databaseRef,
balanceSet: balanceSet,
);
default:
return new WelcomePage(onSignOut: _signOut);
}
}
}
class LoanList extends StatelessWidget {
final VoidCallback onSignOut;
LoanList({this.onSignOut});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: Text('Loans'),
actions: <Widget>[
new FlatButton(
child: new Text(
'Logout',
style: new TextStyle(fontSize: 17.0, color: Colors.white),
),
onPressed: onSignOut,
)
],
),
body: new Container(
padding: EdgeInsets.all(20.0),
alignment: Alignment.bottomCenter,
child: new RaisedButton(
child: new Text(
'New Loan',
style: new TextStyle(color: Colors.white, fontSize: 17.0),
),
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context) => NewLoan()));
},
color: Colors.blue,
),
),
);
}
void addNewLoan() {
print('Add new Loan');
}
}
class WelcomePage extends StatelessWidget {
final VoidCallback onSignOut;
WelcomePage({this.onSignOut});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text('Welcome'),
actions: <Widget>[
new FlatButton(
child: new Text(
'Logout',
style: new TextStyle(fontSize: 17.0, color: Colors.white),
),
onPressed: onSignOut,
)
],
),
body: new Container(
child: new Center(
child: new Text(
'Checking',
style: new TextStyle(fontSize: 32.0),
),
),
),
);
}
}

Flutter Checkbox not working in AlertDialog [duplicate]

I'm trying to create a Radio in a showDialog, however the animation that occurs on Radio does not appear in showDialog.
For example: when tapped in foo2 nothing happens, and when you exit in showDialog and go back to it, foo2 is selected.
Below is the code and a gif showing what is happening:
import "package:flutter/material.dart";
void main() {
runApp(new ControlleApp());
}
class ControlleApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: "My App",
home: new HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
HomePageState createState() => new HomePageState();
}
enum _RadioGroup {
foo1,
foo2
}
class HomePageState extends State<HomePage> {
_RadioGroup _itemType = _RadioGroup.foo1;
void changeItemType(_RadioGroup type) {
setState(() {
_itemType = type;
});
}
void showDemoDialog<T>({ BuildContext context, Widget child }) {
showDialog<T>(
context: context,
child: child,
);
}
#override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(backgroundColor: new Color(0xFF26C6DA)),
body: new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new InkWell(
onTap: (){
showDemoDialog<String>(
context: context,
child: new SimpleDialog(
title: const Text("show"),
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Radio<_RadioGroup>(
groupValue: _itemType,
value: _RadioGroup.foo1,
onChanged: changeItemType
),
const Text("foo1"),
new Radio<_RadioGroup>(
groupValue: _itemType,
value: _RadioGroup.foo2,
onChanged: changeItemType
),
const Text("foo2"),
],
)
],
)
);
},
child: new Container(
margin: new EdgeInsets.only(top: 16.0, bottom: 8.0),
child: new Text("Show"),
),
)
],
),
)
);
}
}
Remember that components are immutable.
When you call showDialog, the content of that dialog won't change even if HomePage does.
The solution is easy. You need to refactor a bit your code to something like :
showDialog(
context: context,
builder: (context) => MyForm()
)
and instead of changing the state of HomePage, you instead change the state of MyForm.
example :
class Test extends StatelessWidget {
void onSubmit(String result) {
print(result);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () => showDialog(context: context, builder: (context) => MyForm(onSubmit: onSubmit)),
child: Text("dialog"),
),
),
);
}
}
typedef void MyFormCallback(String result);
class MyForm extends StatefulWidget {
final MyFormCallback onSubmit;
MyForm({this.onSubmit});
#override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
String value = "foo";
#override
Widget build(BuildContext context) {
return SimpleDialog(
title: Text("My form"),
children: <Widget>[
Radio(
groupValue: value,
onChanged: (value) => setState(() => this.value = value),
value: "foo",
),
Radio(
groupValue: value,
onChanged: (value) => setState(() => this.value = value),
value: "bar",
),
FlatButton(
onPressed: () {
Navigator.pop(context);
widget.onSubmit(value);
},
child: new Text("submit"),
)
],
);
}
}

Resources