I am new to programming with flutter and Im trying to create a pizza app. first you create the pizza, choosing the ingredients, then you get a list of your order. The list works and the qr generator as well but they are from separate tutorials and I am having issues connecting them. I cant seem to pass the order list to the generator.
import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'dart:io';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pizza_app/screens/review.dart';
import 'package:pizza_app/code/pizza.dart';
class GenerateQR extends StatefulWidget {
List<String> _list = new List<String>();
#override
State<StatefulWidget> createState() => GenerateQRState();
GenerateQR(list){
_list = list;
}
}
class GenerateQRState extends State<GenerateQR> {
static const double _topSectionTopPadding = 50.0;
static const double _topSectionBottomPadding = 20.0;
static const double _topSectionHeight = 50.0;
GlobalKey globalKey = new GlobalKey();
List<String> _dataList = new List<String>();
//String _dataString = "Hello from this QR";
String _inputErrorText;
final TextEditingController _textController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('QR Code Generator'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: _captureAndSharePng,
)
],
),
body: _contentWidget(),
);
}
Future<void> _captureAndSharePng() async {
try {
RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
var image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.png').create();
await file.writeAsBytes(pngBytes);
final channel = const MethodChannel('channel:me.alfian.share/share');
channel.invokeMethod('shareFile', 'image.png');
} catch(e) {
print(e.toString());
}
}
_contentWidget() {
final bodyHeight = MediaQuery.of(context).size.height - MediaQuery.of(context).viewInsets.bottom;
return Container(
color: const Color(0xFFFFFFFF),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
top: _topSectionTopPadding,
left: 20.0,
right: 10.0,
bottom: _topSectionBottomPadding,
),
child: Container(
height: _topSectionHeight,
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: TextField(
controller: _textController,
decoration: InputDecoration(
hintText: "Enter a custom message",
errorText: _inputErrorText,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 10.0),
child: FlatButton(
child: Text("SUBMIT"),
onPressed: () {
setState((){
_dataList.add(_list); // This must be wrong
_inputErrorText = null;
});
},
),
)
],
),
),
),
Expanded(
child: Center(
child: RepaintBoundary(
key: globalKey,
child: QrImage(
data: _dataList,// I think that there is an error here too
size: 0.5 * bodyHeight,
onError: (ex) {
print("[QR] ERROR - $ex");
setState((){
_inputErrorText = "Error! Maybe your input value is too long?";
});
},
),
),
),
),
],
),
);
}
}
Use Iterable.Join() to join your list of strings into a single string, using a suitable separator like the pipe (|) symbol:
Handle the case where somebody types the | character into the TextField.
The code that reads the QR code can use String.split() to split the string into a list of strings again.
Related
I have a login screen code like below that has a text button that changes the state of the Login button to Signup or reverse, and want to rewrite it to use GetX library. But I don't know how?
enum AuthMode { Signup, Login }
class AuthenticationScreen extends StatelessWidget {
const AuthenticationScreen({Key? key}) : super(key: key);
AuthMode _authMode = AuthMode.Login;
#override
Widget build(BuildContext context) {
final GlobalKey<FormState> _formKey = GlobalKey();
void _switchAuthMode() {
if (_authMode == AuthMode.Login) {
setState(() {
_authMode = AuthMode.Signup;
= });
_controller!.forward();
} else {
setState(() {
_authMode = AuthMode.Login;
});
_controller!.reverse();
}
}
return Scaffold(
body: Center(
child: Container(
constraints: const BoxConstraints(maxWidth: 400),
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
,
TextButton(
child: Text(
'${_authMode == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} '),
onPressed: _switchAuthMode,
style: TextButton.styleFrom(
padding:
const EdgeInsets.symmetric(horizontal: 30.0, vertical: 4),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
textStyle: TextStyle(color: Theme.of(context).primaryColor),
),
],
),
),
),
);
}
}
I tried some changes like transferring Authmode to the auth_controller file that extends GetxController and add obs after AuthMode _authMode = AuthMode.Login; and try to use obx(()=>) inside the _switchAuthMode() but didn't work.
Try like this:
final authMode= Rx<AuthMode>(AuthMode.Login);
And then on your switchAuthMode method:
authMode.value = AuthMode.Signup; // without setState
And finally, wrap the Text widget with Obx:
Obx(()=> Text('${authMode.value == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} ')
And you can actually make your widget a StatelessWidget.
I have a list like this a = [{'one': 'one', 'two': null, 'three': [{'four': 'four'}]}]
I send it to a function to use it in a post request which in the body should receive a Map, so what I did was this to a[0], the problem is that I get this error The getter 'length' was called on null
I start to review and it treats all the property values as if they were Strings, even the nested list 'three': [{'four': 'four'}], I have tried to send the post in this way http.post (url, body: (recurrence [0] as Map)) but it has not worked, it always gives me the same error, even if in the body I put the properties by hand in the body: {'new property': a [0] [' tres']}, how should one act to solve this problem? Thank you very much for your help
Code:
void _ordersGet() async {
await http.get(url).then((value) {
setState(() {
orders = jsonDecode(value.body);
}
}
orders is sent to a new widget: orderList(orders)
orderList is a listView
ListView.builder(
shrinkWrap: true,
primary: false,
itemCount: orders.length,
itemBuilder: (orders, index) {
return return Card(
elevation: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(orders[index]['facts']),
SizedBox(
width: 4,
),
Text('Cantidad : '),
Text(orders[index]['ITEMS'][0]['jeans']),
SizedBox(
width: 4,
),
IconButton(
onPressed: () => _reorderData(context, orders[index]),
icon: Icon(
Icons.replay_outlined,
color: Theme.of(context).accentColor,
)),
],
),
);
},
);
_reorderData is a function that make a get request, the info in shipped to ReorderModal
ReorderModal it only shows the information and has a button
void _reorderData(BuildContext ctx, order) async {
var data;
var url = 'serverAddress/${order['facts']}';
await http.get(url).then((value) {
data = jsonDecode(value.body);
data[0]['CORPORATION'] = order['corporation'];
showModalBottomSheet(
context: ctx,
builder: (_) {
return ReorderModal(data);
});
}).catchError((onError) {});
}
class ReorderModal extends StatelessWidget {
final List data;
ReorderModal(this.data);
void orderSend(orderInfo) async {
var url = 'serverAddress';
await http.post(url, body: orderInfo[0]).then((value) {
print(jsonDecode(value.body));
}).catchError((onError) {
print(onError);
});
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: Column(children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Column(
children: [
ElevatedButton(
onPressed: () {
orderSend(data);
//print(data);
},
child: Text('ONE Click'))
]),
);
}
}
when i press the ONE Click button execute the function orderSend, orderSend make a post request and the problem described above
This is the simplified code, I know it must be something very simple, but it is giving me a lot of work to solve
Hello I am having issue to understand how to manage properties of a class when it is part of a list of classes
Here are my classes
class BasketItem {
final String itemDescription;
final String itemNote;
BasketItem(
{this.itemDescription,
this.itemNote});
}
class AppData {
static final AppData _appData = new AppData._internal();
List<BasketItem> basketList = [];
factory AppData() {
return _appData;
}
AppData._internal();
}
final appData = AppData();
And here is my List
List<Container> _buildBasketList() {
return appData.basketList.map((bList) {
var container = Container(
child: Builder(
builder: (context) => Dismissible(
key: Key(UniqueKey().toString()),
background: Container(
margin: EdgeInsets.all(8.0),
color: kColorAccent,
child: Align(
alignment: Alignment(-0.90, 0.00),
child: Icon(Icons.add_comment)),
),
onDismissed: (direction) {
final newItemToAdd = BasketItem(
itemDescription: bList.itemDescription,
itemNote: 'xxxxx',);
appData.basketList.add(newItemToAdd);
setState(() {});
appData.basketList.remove(bList);
},
child: Stack(...)
),
),
);
return container;
}).toList();
}
I would like to do the following: when onDismissed get executed I would like to amend the property itemNote to 'xxxxx'. How can I do it? At the moment I remove the BasketItem I have swiped and I create a new BasketItem and I add it to the list. The problem is that this does not seem efficient and it also add the item at the end of the list while I would like to keep it at the same position/index where it was.
Thanks
Approach 1
Make fields in BasketItem non final. So you can amend them.
class BasketItem {
final String itemDescription;
/*final*/ String itemNote;
BasketItem(
{this.itemDescription,
this.itemNote});
}
// onDismissed will change itemNote.
....
onDismissed: (direction) {
setState(() {
bList.itemNote = 'xxxxx';
});
},
...
Approach 2
Replace list contents inline. Don't remove and add
List<Container> _buildBasketList() {
return appData.basketList.asMap().map((index, bList) {
var container = Container(
child: Builder(
builder: (context) => Dismissible(
key: Key(UniqueKey().toString()),
background: Container(
margin: EdgeInsets.all(8.0),
color: kColorAccent,
child: Align(
alignment: Alignment(-0.90, 0.00),
child: Icon(Icons.add_comment)),
),
onDismissed: (direction) {
setState(() {
appData.basketList[index] = BasketItem(
itemDescription: bList.itemDescription,
itemNote: 'xxxxx',);
});
},
child: Stack(...)
),
),
);
return container;
}).toList();
}
I am using Flutter table calendar plugin to make a calendar. In order to put events into the calendar, I have to add data to _events map. I want to get the data from Firestore document, and put the data into _events map. However, I don't know how to do it. I search everywhere but I can't get an answer.
This is my code
class _MemberEventsState extends State<MemberEvents>
with TickerProviderStateMixin {
Map<DateTime, List> _events;
List _selectedEvents;
AnimationController _animationController;
CalendarController _calendarController;
List<String> list = List();
#override
void initState() {
super.initState();
final _selectedDay = DateTime.now();
Firestore.instance
.collection('events')
.document('2019-07-30')
.get()
.then((DocumentSnapshot ds) {
list = List.from(ds['title']);
});
_events = {DateTime.parse("2019-08-01"): list};
_selectedEvents = _events[_selectedDay] ?? [];
_calendarController = CalendarController();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_animationController.forward();
}
#override
void dispose() {
_animationController.dispose();
_calendarController.dispose();
super.dispose();
}
void _onDaySelected(DateTime day, List events) {
print('CALLBACK: _onDaySelected');
setState(() {
_selectedEvents = events;
});
}
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onVisibleDaysChanged');
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
_buildTableCalendar(),
const SizedBox(height: 8.0),
const SizedBox(height: 8.0),
Expanded(child: _buildEventList()),
],
),
);
}
Widget _buildTableCalendar() {
return TableCalendar(
calendarController: _calendarController,
events: _events,
startingDayOfWeek: StartingDayOfWeek.sunday,
calendarStyle: CalendarStyle(
selectedColor: Colors.deepOrange[400],
todayColor: Colors.blueAccent[200],
markersColor: Colors.brown[700],
outsideDaysVisible: false,
),
headerStyle: HeaderStyle(
formatButtonTextStyle:
TextStyle().copyWith(color: Colors.white, fontSize: 15.0),
formatButtonDecoration: BoxDecoration(
color: Colors.deepOrange[400],
borderRadius: BorderRadius.circular(16.0),
),
),
onDaySelected: _onDaySelected,
onVisibleDaysChanged: _onVisibleDaysChanged,
);
}
Widget _buildEventList() {
return ListView(
children: _selectedEvents
.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin:
const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.toString()),
),
))
.toList(),
);
}
}
So in the first step to achieve my goal, I made a document named 2019-07-30, then I made an array in it named title. Then I tried to get the values in the array to a List named list. However, list returned null.
I don't know where I went wrong.
I am new to Flutter, so the question might seem stupid.
Also, I am new to stackoverflow, so if I did any steps wrong on describing the question, please tell me so I can fix it.
I am using Firebase realtime database to retrieve information and then present it in a scrollable DataTable.
To make the DataTable scrollable, I wrapped it up in a ListView, as per the comment of this post:
DataTable - make scrollable, set background colour and fix/freeze header row and first column
This is my code:
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'cprdata.dart';
import 'dart:convert';
class CprAnalysis extends StatefulWidget {
#override
CPRState createState() => CPRState();
}
class CPRState extends State<CprAnalysis> {
///var cpr = UpdateData.getData();
List<FilterData> acData;
List<FilterData> getData() {
var cpr = <FilterData>[];
DatabaseReference cprData = FirebaseDatabase.instance.reference();
cprData.reference().once().then((DataSnapshot snap) {
var d = snap.value;
final jsonE = json.encode(d);
final jsonResponse = json.decode(jsonE);
MyDataList zz = new MyDataList.fromJson(jsonResponse);
zz.myList.forEach((data) {
cpr.add(FilterData(sYMBOL: data.SYMBOL, fORECAST: data.FORECAST));
}
);
},
);
print(cpr);
return cpr;
}
#override
void initState() {
super.initState();
acData = getData();
}
Widget bodydata() => Expanded(
child: ListView(
///shrinkWrap: true,
padding: const EdgeInsets.all(8.0),
childern: <Widget>[
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columns: <DataColumn>[
DataColumn(
label: Text("Symbol"),
numeric: false,
),
DataColumn(
label: Text("Forecast"),
numeric: false,
),
],
rows: acData.map((data) =>
DataRow(
cells: [
DataCell(
Text(data.sYMBOL),
showEditIcon: false,
placeholder: false,
),
DataCell(
Text(data.fORECAST),
showEditIcon: false,
placeholder: false,
)
],
),
)
.toList()
),
),
]
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("CPR Analysis"),
),
body: Container(
child: bodydata(),
),
);
}
}
class FilterData {
String sYMBOL, fORECAST;
FilterData({
this.sYMBOL,
this.fORECAST});
}
Expected output: Scrollable DataTable.
Actual output: error: The named parameter 'childern' isn't defined under ListView()
You misspelled children as childern in your code.
Make your ListView code as -
ListView(
children: <Widget> [
//Your remaining code
]
),