Using Title in Flutter - android

import 'package:flutter/material.dart';
class CategoryMealsScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
final routeArgs =
ModalRoute.of(context)!.settings.arguments as Map<String, String>;
final categoryTitle = routeArgs['title'];
final categoryId = routeArgs['id'];
return Scaffold(
appBar: AppBar(
title: Text(categoryTitle),
),
body: Center(
child: Text(
'The Recipes For The Category!',
),
),
);
}
}
I got error with this code and the error in title: Text(categoryTitle),what should i do to fix it?

you can convert it to string
Text(categoryTitle.toString());

You are facing this error because the type of categoryTitle might not be in String format. You can solve it by follwing ways:
You can convert categoryTitle to String when you are first assigning like this:
final String categoryTitle = routeArgs['title'].toString();
You can convert to String when you want to display in Widgets in the UI like this:
appBar: AppBar(
title: Text(categoryTitle.toString()),
),
However, I would suggest to convert to the type you need while assigning it only so that you don't have to worry about type conversion later on.

Related

how initialize variable in GetX controller?

I have GetxController with the late Map data and I won't fill this in onInit() after searching on the database, but when the page is open the emulator shows the red screen with the not initialize error.
I need the dataMap1 and 2 for showing the PieChart when the screen opens.
I think this occurred because I use the Future function, But I do not know how to fix this.
this is my entire controller code.
import 'package:get/get.dart';
import 'package:hive/hive.dart';
class ReportScreenController extends GetxController{
late Map<String, double> dataMap1;
final Map<String, double> dataMap2 = {
"ورزشی": 5,
"خصوصی": 3,
"اداری": 5,
"دسته بندی نشده": 3,
};
#override
Future<void> onInit() async {
super.onInit();
//categoryScrollController.position.ensureVisible()
await reportFunction();
}
Future<void> reportFunction() async {
//dataMap1
var taskBox = await Hive.openBox('task');
var taskFinish =
taskBox.values.where((task) => task.status == true).toList();
var taskUnFinish =
taskBox.values.where((task) => task.status == false).toList();
double test = double.parse(taskFinish.length.toString());
double test2 = double.parse(taskUnFinish.length.toString());
print(test.toString());
print(test2.toString());
dataMap1.addAll({
'رو زمین مانده': test2,
'تکمیل شده': test,
});
}
}
my view code is
class ReportScreen extends GetView<ReportScreenController> {
const ReportScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
background(),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Column(
children: [
const Text(':نمودار فعالیت', style: boldText),
MyPieChart(dataMap: controller.dataMap1),
const Text(':نمودار وظایف', style: boldText),
MyPieChart(dataMap: controller.dataMap2),
],
),
),
],
),
);
}
}
You forgot to initialize dataMap1, simply in onInit() add dataMap1 = {}.
I think you also dont need a late modifier, just use final final Map<String, double> dataMap1 = {};, but everybody is choosing thier weapons.
In addition i think there will be problem with that how you use controller.dataMap1 in your view. Most likely you dont rebuild your view after you finally initialize / populate dataMap1.
Update:
You can change in controller:
late Map<String, double> dataMap1; to final RxMap<String, double> dataMap1 = RxMap();, and in your view:
MyPieChart(dataMap: controller.dataMap1), to Obx(() => MyPieChart(dataMap: controller.dataMap1.value))

Failed assertion: boolean expression must not be null upon declaring getter isEmpty

I'm making a favorites list viewer for my application. I wanted to make so when the users haven't had anything added to their favorites, it will show a text like a "You have no favorites" of some sorts.
Widget build(BuildContext context) {
var favoriteBloc = Provider.of<FavoriteBloc>(context);
SizeConfig().init(context);
return Scaffold(
resizeToAvoidBottomInset: true,
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Expanded(
child: favoriteBloc.isEmpty?
const Center(
child: Text(
"Anda belum memiliki favorites",
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.bold
),
)
)
Since I'm using provider, i also have a favorites_provider.dart. I've defined isEmpty as null here since it says that the getter was not available for favoriteBloc.
import 'package:aplikasi_jurnal_mobile/models/journals.dart';
import 'package:flutter/cupertino.dart';
class FavoriteBloc with ChangeNotifier {
int _count = 0;
List<JournalModel> items = [];
get isEmpty => null;
void addItems(JournalModel data) {
items.add(data);
notifyListeners();
}
int get count {
return _count;
}
List<JournalModel> get itemsList {
return items;
}
}
Here is the model to my item list, favoriteBloc pretty much consists of the following as well. It gets the JournalModel after the user has pressed on the favorite button.
class JournalModel{
String? id;
String? journalTitle;
int? journalReleaseYear;
String? author;
String? topic;
String? fileLocation;
bool status;
JournalModel({
this.id,
this.journalTitle,
this.journalReleaseYear,
this.author,
this.topic,
this.fileLocation,
this.status = false
});
}
When i try to run the application however, it throws the error stated at the title. Does it have to do something with the bool status in the model?
I've essentially implemented the same thing i did on my search function and it works just fine.

Flutter chat app on Firebase, StreamBuilder reloads blinking and calls on null value when ListView is created

I'm making a FreeLancer app with a chat function. First, I want the chat list that renders chat tiles from Firebase so I use GetX Stream (is this like streamBuilder?) to render the chat tile representing, and in that chat tile (I'm using ListTile) the subtitle text is pulled from FireStore from the latest message using StreamBuilder
Chat List Screen
final user = FirebaseAuth.instance.currentUser;
return user == null
? const Center(
child: Text('Please login to use Chat'),
)
: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () async {
ChatService().addRoom(randomString());
},
child: const Icon(FontAwesomeIcons.solidMessage),
),
appBar: AppBar(
title: const Text('Chats'),
centerTitle: true,
),
body: GetX<ChatController>(
init: ChatController(),
builder: (roomList) {
return ListView.builder(
itemCount: roomList.rooms.length,
itemBuilder: (context, index) {
return ChatTile(roomList.rooms[index]);
},
);
},
),
Chat Tile
final db = FirebaseFirestore.instance.collection('Rooms').doc(room.roomId);
final stream = db.snapshots();
var roomName = 'Loading...';
return StreamBuilder(
stream: stream,
builder: (context, snapshot) {
final roomInfo = snapshot.data as dynamic;
return Column(
children: [
InkWell(
onTap: () {},
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.08,
child: Center(
child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 10),
leading: const FlutterLogo(size: 50),
title: Text(roomInfo['roomName']),
subtitle: LastMessage(room.roomId),
trailing: Text(timeago.format(
(roomInfo['lastestMsg'] as Timestamp).toDate())),
),
),
),
),
const Divider()
],
);
},
);
Latest Message
final db = FirebaseFirestore.instance.collection('Rooms').doc(roomId);
final stream = db
.collection('message')
.orderBy('createdDate', descending: true)
.snapshots();
return StreamBuilder<QuerySnapshot>(
stream: stream,
builder: (context, snapshot) {
final messages = snapshot.data!.docs;
final message = messages.first.data() as dynamic;
return Text(
message['content'],
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
});
Chat Room Model
String roomId;
String roomName;
DateTime createDate;
bool isDeleted;
DateTime lastestMsg;
List<String> members;
ChatRoom({
required this.roomId,
required this.roomName,
required this.createDate,
required this.isDeleted,
required this.lastestMsg,
required this.members,
});
factory ChatRoom.fromMap(Map<String, dynamic> map) {
return ChatRoom(
roomId: map['roomId'] as String,
roomName: map['roomName'] as String,
createDate: (map['createDate'] as Timestamp).toDate(),
isDeleted: map['isDeleted'] as bool,
lastestMsg: (map['lastestMsg'] as Timestamp).toDate(),
members: List<String>.from(
(map['members'] as List<dynamic>),
),
);
}
String toJson() => json.encode(toMap());
factory ChatRoom.fromJson(String source) =>
ChatRoom.fromMap(json.decode(source) as Map<String, dynamic>);
Message Model
String senderId;
String content;
DateTime createdDate;
List<String> seenBy;
bool isDeleted;
FreeLanceMessage({
required this.senderId,
required this.content,
required this.createdDate,
required this.seenBy,
required this.isDeleted,
});
factory FreeLanceMessage.fromMap(Map<String, dynamic> map) {
return FreeLanceMessage(
senderId: map['senderId'] as String,
content: map['content'] as String,
createdDate: (map['createdDate'] as Timestamp).toDate(),
seenBy: List<String>.from(
(map['seenBy'] as List<dynamic>),
),
isDeleted: map['isDeleted'] as bool,
);
}
String toJson() => json.encode(toMap());
factory FreeLanceMessage.fromJson(String source) =>
FreeLanceMessage.fromMap(json.decode(source) as Map<String, dynamic>);
Error When the Chat list screen gets mounted to the tree, it only appears for few milliseconds, when I add a new chat, the chat latest message doesn't show an error after this
I use random string so don't mind the title and the msg
Edit: I can use streambuilder and check for connection state but the screen blinks for any data change and I don't want that
so my question is, is this the right way to do this? is there another way? if so, how can I improve this

I can't manage to make an api call using a parsed integer

So I am building an app using flutter, I am new to flutter and would need help on a little something.
So for the context, my app is connected to a REST API, which was tied to a ruby on rails web app for a fictional elevators company (for learning purposes) and what I am trying to achieve is to change the status of an elevator using a text field in my app, I almost got it, the only thing is that whenever I do my api call like this:
class DetailScreen extends StatelessWidget {
// Declare a field that holds the Todo.
final Elevator elevator;
// In the constructor, require a Todo.
DetailScreen({Key key, #required this.elevator}) : super(key: key);
Future _changeStatus(elevator) async {
//Fetch the data from the api
// ignore: non_constant_identifier_names
var id = elevator.id.toString();
var holder = id.toString();
var url = 'https://rocketcrybaby.azurewebsites.net/api/elevators/'+holder;
var response = await http.put(
url, body: {'status': '${_statusController.text}'});
if (_statusController.text != "active"|| _statusController.text != "inactive"){
return "Error not a valid status !";
}
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
//print(await http.read('https://example.com/foobar.txt'));
return "sucess";
}
#override
Widget build(BuildContext context) {
// Use the Todo to create the UI.
return Scaffold(
appBar: AppBar(
title: Text("Elevator # " +elevator.id.toString()),
),
body: Center(
child: Center(
child: TextField(
controller: _statusController
),
)
),
floatingActionButton: FloatingActionButton(onPressed: () async => [ await _changeStatus(elevator.id.toString()), print(elevator.status)]),
);
}
it returns me this error:
E/flutter (18441): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance getter 'id'.
E/flutter (18441): Receiver: "3"
E/flutter (18441): Tried calling: id
I really don't know what to do anymore I tried every trick I had in my book :/
for reference here's the Elevator class
class Elevator {
final String status;
final String model;
final int id;
Elevator({this.status, this.model, this.id}); //Elevator Constructor
factory Elevator.fromJson(Map<String, dynamic> json) { //Parse the infos as Json String
return Elevator(
status: json['status'],
model: json['model'],
id: json['id']
);
}
}
Additionally here's the output of an elevator in my api
{
"id": 3,
"column_id": 1,
"serial_number": 7204019747089,
"model": "Excelium",
"building_type": "Hybrid",
"status": "Inactive",
"date_service_since": "2018-03-09T00:00:00",
"date_last_inspection": "2019-02-19T00:00:00",
"inspection_certificate": "Yes",
"information": "Dori",
"notes": "Dolores aut et. Ea optio rem. Provident exercitationem ut.",
"created_at": "2020-04-09T20:41:55",
"updated_at": "2020-04-09T20:41:55"
},
Solution:
class DetailScreen extends StatelessWidget {
// Declare a field that holds the Todo.
final Elevator elevator;
// In the constructor, require a Todo.
DetailScreen({Key key, #required this.elevator}) : super(key: key);
Future _changeStatus(Elevator elevator) async {
//Fetch the data from the api
// ignore: non_constant_identifier_names
var id = elevator.id.toString();
var holder = id.toString();
var url = 'https://rocketcrybaby.azurewebsites.net/api/elevators/'+holder;
var response = await http.put(
url, body: {'status': '${_statusController.text}'});
if (_statusController.text != "active"|| _statusController.text != "inactive"){
return "Error not a valid status !";
}
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
//print(await http.read('https://example.com/foobar.txt'));
return "sucess";
}
#override
Widget build(BuildContext context) {
// Use the Todo to create the UI.
return Scaffold(
appBar: AppBar(
title: Text("Elevator # " +elevator.id.toString()),
),
body: Center(
child: Center(
child: TextField(
controller: _statusController
),
)
),
floatingActionButton: FloatingActionButton(onPressed: () async => [ await _changeStatus(elevator), print(elevator.status)]),
);
}
Tip: Always use Variable type while declaring the variable to avoid these errors and for good practice.
Thanks.
Thats because your method : Future _changeStatus(elevator) async actually takes Elevator elevator, but you are providing elevator.id.toString() which is a String.
Change the method parameter's type and in FAB's onPressed change to await _changeStatus(elevator).

Can a flutter variable be used in a php url

I want to use the value of a flutter variable in PHP URL.what can I do to pass the value of the variable.
I've tried passing value or can say a id in a web view in flutter but it is printing the string not the value of the variable.
`
String url = "http://10.0.2.2/pre_beta_02/dummy.php?therapist_id=value";
class NextPage extends StatefulWidget{
//List list;
String value;
//NextPage({this.value});
NextPage({Key key,this.value}):super (key: key);
#override
_Nextpagestate createState() => new _Nextpagestate();
}
class _Nextpagestate extends State<NextPage>{
#override
Widget build(BuildContext context) {
return WebviewScaffold(
appBar: new AppBar(
title: new Text('${widget.value}'),
),
url: url,
);
}
}
`
I expect the output as "value = 5" but the actual output coming is "value"
This should do it:
return WebviewScaffold(
appBar: new AppBar(
title: new Text('${widget.value}'),
),
url: "http://10.0.2.2/pre_beta_02/dummy.php?therapist_id=${widget.value}",
);

Categories

Resources