Non-Nullable instance field - android

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime _selectedDate;
void _submitData() {
if (_amountController.text.isEmpty) {
return;
}
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0 || _selectedDate == null) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
print('...');
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen!'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
),
),
// ignore: deprecated_member_use
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(
'Choose Date',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onPressed: _presentDatePicker,
),
],
),
),
// ignore: deprecated_member_use
RaisedButton(
child: Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).primaryColor,
onPressed: _submitData,
),
],
),
),
);
}
}
Here in the above code. _selectedDate is giving me error. I just looked after adding late but its not also error and here is the error message,
Non-nullable instance field '_selectedDate' must be initialized.
Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'.

You can make it nullable like this:
DateTime? _selectedDate;

Related

why I got the error in DateTime _selectedDate;?

this is my code
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
State<NewTransaction> createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime _selectedDate;
void _submitData() {
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
print('...');
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
controller: _amountController,
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen!'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
),
),
TextButton(
child: Text(
'Choose Date',
style: TextStyle(
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold,
),
),
onPressed: _presentDatePicker,
)
],
),
),
ElevatedButton(
child: Text(
'Add Transaction',
style: TextStyle(
color: Colors.white,
),
),
onPressed: _submitData,
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith(
(states) {
return Colors.purple;
},
),
),
),
],
),
),
);
}
}
there's a redline on DateTime _selectedDate;
what should I do?
You're trying to make it null in the code so that you check over it with e _selectedDate == null.
well, you can tell Dart that it can be null from its declaration with a ?:
DateTime? _selectedDate; // add ?

Flutter: DatePicker not picking the selected date

I am building a personal expenses app using flutter. I open modal sheet whereby I enter my new transactions for a particular expense. In that modal sheet I use showDatePicker() to open a calendar to pick my date. The issue I am facing is that when I open the sheet, initially it shows No date chosen and when I choose a date it displays the date I have chosen but when I click on the add transaction button so I can display the same in a customized list, the date shown is of the present i.e. DateTime.now() instead of the one I have picked.
The following is the code for adding a new transaction:
// ignore_for_file: deprecated_member_use
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
State<NewTransaction> createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime? _selectedDate;
void _submitData() {
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
);
Navigator.of(context).pop(); // closes the top most screen that is opened
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2022),
lastDate: DateTime.now())
.then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: const EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: const InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: const InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// amountInput = val;
// },
),
Container(
height: 70,
child: Row(children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen'
: "Picked Date: ${DateFormat.yMd().format(_selectedDate!)}",
),
),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: const Text("Choose Date",
style: TextStyle(fontWeight: FontWeight.bold)),
onPressed: _presentDatePicker,
)
]),
),
RaisedButton(
child: const Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button?.color,
onPressed: _submitData,
)
],
),
),
);
}
}
I think you need to parse _selectedDate variable into addTx function to access the value on the parent screen.
widget.addTx(
enteredTitle,
enteredAmount,
_selectedDate
);
because your _selectedDate variable is your local variable.

_Cast Error : Null check operator used on a null value [duplicate]

This question already has answers here:
Null check operator used on a null value
(12 answers)
Closed last year.
I am new to programming and don't know how to solve this issue.
I am using the java version of 8 and using Android Studio to make apps with Flutter.
I have been making a to-do list app, and a cast error happens when
I make a new list
I update a list
I delete a list
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ToDo List',
debugShowCheckedModeBanner: false,
theme: ThemeData(
fontFamily: "NanumSquare",
primaryColor: Color(0xFF424874), //primary color
),
home: HomeScreen()
);
}
}
this is the main.dart
the error appears on the Home Screen.
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late Future<List<Note>> _noteList;
final DateFormat _dateFormatter = DateFormat("MMM dd, yyyy");
DatabaseHelper _databaseHelper = DatabaseHelper.instance;
void initState() {
super.initState();
_updateNoteList();
}
_updateNoteList() {
_noteList = DatabaseHelper.instance.getNoteList();
}
Widget _buildNote(Note note) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 25),
child: Column(
children: [
Container(
margin: EdgeInsets.all(5),
color: Color(0xFFDCD6F7),
child: ListTile(
title: Text(
note.title!,
style: TextStyle(
fontSize: 20,
color: Color(0xFF424874),
decoration: note.status == 0
? TextDecoration.none
: TextDecoration.lineThrough),
),
subtitle: Text(
"${_dateFormatter.format(note.date!)}-${note.priority}",
style: TextStyle(
fontSize: 15,
color: Color(0xFF424874),
decoration: note.status == 0
? TextDecoration.none
: TextDecoration.lineThrough),
),
trailing: Checkbox(
onChanged: (value) {
note.status = value! ? 1 : 0;
DatabaseHelper.instance.updateNote(note);
_updateNoteList();
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (_) => HomeScreen())
);
},
activeColor: Color(0xFFA6B1E1),
value: note.status == 1 ? true : false,
),
onTap: () => Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => AddNoteScreen(
updateNoteList: _updateNoteList(),
note: note
)
),
),
),
),
Divider(
height: 5,
color: Color(0xFFA6B1E1),
thickness: 2,
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFF4EEFF),
floatingActionButton: FloatingActionButton(
backgroundColor: Color(0xFF424874),
onPressed: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => AddNoteScreen(
updateNoteList: _updateNoteList(),
),
));
},
child: Icon(Icons.add),
),
body: FutureBuilder(
future: _noteList,
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final int completedNoteCount = snapshot.data!.where((Note note) => note.status == 1).toList().length;
return ListView.builder(
padding: EdgeInsets.symmetric(vertical: 80),
itemCount: int.parse(snapshot.data!.length.toString()) + 1,
itemBuilder: (BuildContext context, int index) {
if (index == 0) {
return Padding(
padding:
EdgeInsets.symmetric(horizontal: 40, vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"My Notes",
style: TextStyle(
color: Color(0xFF424874),
fontSize: 40,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"$completedNoteCount of ${snapshot.data.length}",
style: TextStyle(
color: Color(0xFFA6B1E1),
fontSize: 20,
fontWeight: FontWeight.w600),
),
],
),
);
}
return _buildNote(snapshot.data![index-1]);
});
}));
}
}
The error message is as below.
======== Exception caught by gesture ===============================================================
The following _CastError was thrown while handling a gesture:
Null check operator used on a null value
When the exception was thrown, this was the stack:
#0 _AddNoteScreenState._delete (package:crud_sqlite_app/screens/add_note_screen.dart:80:26)
#1 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#2 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
#3 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
#4 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#e7613
debugOwner: GestureDetector
state: ready
won arena
finalPosition: Offset(150.8, 655.2)
finalLocalPosition: Offset(110.8, 46.2)
button: 1
sent tap down
====================================================================================================
and this is the add_note_screen.dart
class AddNoteScreen extends StatefulWidget {
final Note? note;
final Function? updateNoteList;
AddNoteScreen({this.note, this.updateNoteList});
#override
_AddNoteScreenState createState() => _AddNoteScreenState();
}
class _AddNoteScreenState extends State<AddNoteScreen> {
final _formKey = GlobalKey<FormState>();
String _title = "";
String _priority = "Low";
String btnText = "Add Note";
String titleText = "Add Note";
DateTime _date = DateTime.now();
TextEditingController _dateController = TextEditingController();
final DateFormat _dateFormatter = DateFormat("MMM dd, yyyy");
final List<String> _priorities = ["Low", "Medium", "High"];
#override
void initState(){
super.initState();
if(widget.note != null) {
_title = widget.note!.title!;
_date = widget.note!.date!;
_priority = widget.note!.priority!;
setState(() {
btnText = "Update Note";
titleText = "Update Note";
});
}
else {
setState(() {
btnText = "Add Note";
titleText = "Add Note";
});
}
_dateController.text = _dateFormatter.format(_date);
}
#override
void dispose() {
_dateController.dispose();
super.dispose();
}
_handleDatePicker() async {
final DateTime? date = await showDatePicker(
context: context,
initialDate: _date,
firstDate: DateTime(2000),
lastDate: DateTime(2100));
if (date != null && date != _date) {
setState(() {
_date = date;
});
_dateController.text = _dateFormatter.format(date);
}
}
_delete() {
DatabaseHelper.instance.deleteNote(widget.note!.id!);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_)=> HomeScreen()
)
);
widget.updateNoteList!();
}
_submit() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print("$_title, $_date, $_priority");
Note note = Note(
title: _title,
date: _date,
priority: _priority
);
if (widget.note == null){
note.status = 0;
DatabaseHelper.instance.insertNote(note);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=> HomeScreen())
);
}
else{
note.id = widget.note!.id;
note.status = widget.note!.status;
DatabaseHelper.instance.updateNote(note);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=> HomeScreen())
);
}
widget.updateNoteList!();
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFF4EEFF),
body: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: SingleChildScrollView(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 40, vertical: 80),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: () => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => HomeScreen(),
)
),
child: Icon(
Icons.arrow_back,
size: 30,
color: Color(0xFFA6B1E1),
),
),
SizedBox(
height: 20.0,
),
Text(
titleText,
style: TextStyle(
color: Color(0xFF424874),
fontSize: 40,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Form(
key: _formKey,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: TextFormField(
style: TextStyle(fontSize: 18),
decoration: InputDecoration(
labelText: "Title",
labelStyle: TextStyle(fontSize: 18),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10))),
validator: (input) => input!.trim().isEmpty
? "Please enter a note title"
: null,
onSaved: (input) => _title = input!,
initialValue: _title,
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: TextFormField(
readOnly: true, //hide keyboard
controller: _dateController,
style: TextStyle(fontSize: 18),
onTap: _handleDatePicker,
decoration: InputDecoration(
labelText: "Date",
labelStyle: TextStyle(fontSize: 18),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10))),
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: DropdownButtonFormField(
isDense: true,
icon: Icon(Icons.arrow_drop_down_circle),
iconSize: 22,
iconEnabledColor: Color(0xFF424874),
items: _priorities.map((String priority) {
return DropdownMenuItem(
value: priority,
child: Text(
priority,
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
));
}).toList(),
style: TextStyle(fontSize: 18),
decoration: InputDecoration(
labelText: "Priority",
labelStyle: TextStyle(fontSize: 18),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
)
),
// validator: (input) => _priority == null ? "Please",
onChanged: (value) {
setState(() {
_priority = value.toString();
});
},
value: _priority,
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 20),
height: 60.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30)),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Theme.of(context).primaryColor)
),
child: Text(
btnText,
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: _submit,
),
),
widget.note != null ? Container(
margin: EdgeInsets.symmetric(vertical: 20),
height: 60,
width: double.infinity,
decoration: BoxDecoration(
color: Color(0xFF424874),
borderRadius: BorderRadius.circular(30)
),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Theme.of(context).primaryColor)
),
child: Text("Delete Note",
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
onPressed: _delete,
),
): SizedBox.shrink()
],
),
)
],
),
),
),
),
);
}
}
I am sorry the code is too long.
If you can help me, I will really appreciate it.
Thank you!
This error occurs when you use a bang operator (!) on a nullable instance which wasn't initialized. This operator should only be used when you are sure that the variable cannot be null, I don't recommend using it. Check out this answer

flutter firestore update data method

I'm trying to update the card data I brought from firestore
when I use onTap in Inkwell I want to change data in this card.
this is my search service. I am using this for bring data from firestore
how can I make update function on this situation. thanks for help
class SearchService {
List<Future<QuerySnapshot>> searchByName() {
return [
Firestore.instance
.collection('dis')
.where('no')
.orderBy('date', descending: true )
.getDocuments(),
];
}
}
this is my Card code
Widget buildResultCard(BuildContext context , data) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
elevation: 5,
child: ExpansionCard(
title: Column(
children: [
Row(
children: [
Padding(
padding: EdgeInsets.fromLTRB(5, 0, 5, 1),
child: Text(data['isim'],
style: GoogleFonts.montserrat(color: Colors.blueGrey[700], fontSize: 20 , textStyle: TextStyle(fontWeight: FontWeight.w400)),
textAlign: TextAlign.center,
),
),
InkWell(
child: Icon(
Icons.update,
color: Colors.white54,
),
onTap: (){//I want to set update function here//
},
)
],
),
);
}
and this is my adddata function
Future<void> addData(carData) async {
if (isLoggedIn()) {
Firestore.instance.collection('dis').add(carData).catchError((e) {
print(e);
});
} else {
print('You need to be logged in');
}
}
a little bit long but this is my addmethod
crudMedthods crudObj = new crudMedthods();
Future<bool> addDialog(BuildContext context) async {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
final _width = MediaQuery.of(context).size.width;
return AlertDialog(
title: Text('Temsilci Verisi Ekleyin.', style: GoogleFonts.montserrat(color: Colors.black54,
fontSize: 22 , textStyle: TextStyle(fontWeight: FontWeight.w300)),
textAlign: TextAlign.center,),
content: SingleChildScrollView(
child: Container(
width: _width,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
children: [
TextField(
onTap: (){
showDatePicker(context: context,
initialDate: _dateTime == null ? DateTime.now() : _dateTime,
firstDate: DateTime(2000),
lastDate: DateTime(2030)).then((date) {
setState(() {
_dateTime = date;
});
});
},
decoration: InputDecoration(hintText: _dateTime == null ? 'Uygulama Sıralama
Takvimi Giriniz' : _dateTime.toString()),
onChanged: (value) {
this._dateTime = value as DateTime;
},
),
],
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Temsilci'),
onChanged: (value) {
this.temsilci = value;
},
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Sıra No'),
onChanged: (value) {
this.sirano = value;
},
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Tarih'),
onChanged: (value) {
this.tarih = value;
},
),
SizedBox(height: 5.0),
TextField(
decoration: InputDecoration(hintText: 'Veri Kaynağı'),
onChanged: (value) {
this.verik = value;
},
),
],
),
),
),
actions: <Widget>[
FlatButton(
child: Text('Verileri Sisteme Ekleyin'),
textColor: Colors.blue,
onPressed: () {
Navigator.of(context).pop();
crudObj.addData({
'date': this._dateTime,
'no': this.no,
'temsilci': this.temsilci,
'sıra no': this.sirano,
'tarih': this.tarih,
'veri kaynağı': this.verik,
}).then((result) {
dialogTrigger(context);
}).catchError((e) {
print(e);
});
},
)
],
);
});
}

MyAppState is not displaying anything

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:qrscan/qrscan.dart' as scanner;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.grey[300],
body: Builder(
builder: (BuildContext context) {
return ListView(
children: <Widget>[
_qrCodeWidget(this.bytes, context),
Container(
color: Colors.white,
child: Column(
children: <Widget>[
TextField(
controller: this._inputController,
keyboardType: TextInputType.url,
textInputAction: TextInputAction.go,
onSubmitted: (value) => _generateBarCode(value),
decoration: InputDecoration(
prefixIcon: Icon(Icons.text_fields),
helperText: 'Please input your code to generage qrcode image.',
hintText: 'Please Input Your Code',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
TextField(
controller: this._outputController,
maxLines: 2,
decoration: InputDecoration(
prefixIcon: Icon(Icons.wrap_text),
helperText: 'The barcode or qrcode you scan will be displayed in this area.',
hintText: 'The barcode or qrcode you scan will be displayed in this area.',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
this._buttonGroup(),
SizedBox(height: 70),
],
),
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _scanBytes(),
tooltip: 'Take a Photo',
child: const Icon(Icons.camera_alt),
),
),
);
}
Widget _qrCodeWidget(Uint8List bytes, BuildContext context) {
return Padding(
padding: EdgeInsets.all(20),
child: Card(
elevation: 6,
child: Column(
children: <Widget>[
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Icon(Icons.verified_user, size: 18, color: Colors.green),
Text(' Generate Qrcode', style: TextStyle(fontSize: 15)),
Spacer(),
Icon(Icons.more_vert, size: 18, color: Colors.black54),
],
),
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 9),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4), topRight: Radius.circular(4)),
),
),
Padding(
padding: EdgeInsets.only(
left: 40, right: 40, top: 30, bottom: 10),
child: Column(
children: <Widget>[
SizedBox(
height: 190,
child: bytes.isEmpty
? Center(
child: Text('Empty code ... ',
style: TextStyle(color: Colors.black38)),
)
: Image.memory(bytes),
),
Padding(
padding: EdgeInsets.only(top: 7, left: 25, right: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
flex: 5,
child: GestureDetector(
child: Text(
'remove',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.left,
),
onTap: () =>
this.setState(() => this.bytes = Uint8List(0)),
),
),
Text('|', style: TextStyle(fontSize: 15, color: Colors
.black26)),
Expanded(
flex: 5,
child: GestureDetector(
onTap: () async {
final success = await ImageGallerySaver.saveImage(
this.bytes);
SnackBar snackBar;
if (success) {
snackBar = new SnackBar(content: new Text(
'Successful Preservation!'));
Scaffold.of(context).showSnackBar(snackBar);
} else {
snackBar =
new SnackBar(content: new Text('Save failed!'));
}
},
child: Text(
'save',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.right,
),
),
),
],
),
)
],
),
),
Divider(height: 2, color: Colors.black26),
],
),
),
);
}
Widget _buttonGroup() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: () => _generateBarCode(this._inputController.text),
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/generate_qrcode.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Generate")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scan,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/scanner.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scanPhoto,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/albums.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan Photo")),
],
),
),
),
),
),
],
);
}
Future _scan() async {
String barcode = await scanner.scan();
if (barcode == null) {
print('nothing return.');
} else {
this._outputController.text = barcode;
}
}
Future _scanPhoto() async {
String barcode = await scanner.scanPhoto();
this._outputController.text = barcode;
}
Future _scanPath(String path) async {
String barcode = await scanner.scanPath(path);
this._outputController.text = barcode;
}
Future _scanBytes() async {
File file = await ImagePicker.pickImage(source: ImageSource.camera);
Uint8List bytes = file.readAsBytesSync();
String barcode = await scanner.scanBytes(bytes);
this._outputController.text = barcode;
}
Future _generateBarCode(String inputCode) async {
Uint8List result = await scanner.generateBarCode(inputCode);
this.setState(() => this.bytes = result);
}
}
class MyAppState extends State<MyApp> {
Future<SharedPreferences> _sPrefs = SharedPreferences.getInstance();
final TextEditingController controller = TextEditingController();
List<String> listOne, listTwo;
#override
void initState() {
super.initState();
listOne = [];
listTwo = [];
}
Future<Null> addString() async {
final SharedPreferences prefs = await _sPrefs;
listOne.add(controller.text);
prefs.setStringList('list', listOne);
setState(() {
controller.text = '';
});
}
Future<Null> clearItems() async {
final SharedPreferences prefs = await _sPrefs;
prefs.clear();
setState(() {
listOne = [];
listTwo = [];
});
}
Future<Null> getStrings() async {
final SharedPreferences prefs = await _sPrefs;
listTwo = prefs.getStringList('list');
setState(() {});
}
Future<Null> updateStrings(String str) async {
final SharedPreferences prefs = await _sPrefs;
setState(() {
listOne.remove(str);
listTwo.remove(str);
});
prefs.setStringList('list', listOne);
}
#override
Widget build(BuildContext context) {
getStrings();
return Center(
child: ListView(
children: <Widget>[
TextField(
controller: controller,
decoration: InputDecoration(
hintText: 'Type in something...',
)),
RaisedButton(
child: Text("Submit"),
onPressed: () {
addString();
},
),
RaisedButton(
child: Text("Clear"),
onPressed: () {
clearItems();
},
),
Flex(
direction: Axis.vertical,
children: listTwo == null
? []
: listTwo
.map((String s) => Dismissible(
key: Key(s),
onDismissed: (direction) {
updateStrings(s);
},
child: ListTile(
title: Text(s),
)))
.toList(),
)
],
),
);
}
}
Here the first Appstate creates a Qr code reader. Second is for creating an input controller with shared preferences that can store and retrieve data locally. But when running the code the app displays only the qrscan part and 2nd is not working. I'm new to Flutter. I've just started working on Android Studio. Can anybody help please?
Try to call Another class from home property of the MyApp class.
As you can see in this image
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
//Here I have called MyWidget Class
home: MyWidget()
);
}
}
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(

Categories

Resources