check data is in array flutter - flutter

i create database to store 'post like' and want to check the 'user_id_liked' has like the post or not.
this is the array model from the database. i decided to select all items from database and store it to that array. for example i want to check if "id-2" is in that array or not. how can i do that programatically on flutter? i try like this before but it seems that i cant get result that i want.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.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(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List TotalLike = [];
Future getLike() async {
var response = await http
.post(Uri.parse(url), body: {
"id_post": "post-9d18d0a280",
});
if (response.statusCode == 200) {
setState(() {
try {
TotalLike = json.decode(response.body);
} catch (e) {
print(e);
}
});
setState(() {
TotalLike;
print(TotalLike);
});
return TotalLike;
}
}
#override
void initState() {
getLike();
super.initState();
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Container(
width: 400,
height: 400,
color: TotalLike.contains("id-2") ? Colors.amber : Colors.pink,
)
],
),
);
}
}

var contain = someDataModel.comments.where((element) => element['Id'] == 'id-2');
if (contain.isEmpty){
_isILike = false;
} else {
_isILike = true;
}

Related

Flutter rest GETX map inside Obx not refreshing data on gui side

Hello I have simple script I download data from from Rest api , there is my controller
and when I submit the button I Clear the list inside object Employee, after click I call the deleteEmployee() (int the future CRUD operations per row inside table,) , data are cleared, but data inside widget they are not refreshed. and I would like somethin more with that I need to show in table and make same operation per row.
I cant figure where is a problem.
after click the button must look like
class EmployeeController extends GetxController {
var empData = <Employe>[].obs;
#override
void onInit() {
fetchEmployee();
super.onInit();
}
void fetchEmployee() async {
final response =
await http.get(
Uri.parse('http://dummy.restapiexample.com/api/v1/employees'));
if (response.statusCode == 200) {
final string = response.body;
final parsed = json.decode(string);
Employe emp = Employe.fromJson(parsed);
Employe empx = Employe( message: "sampleTest", status: '123', data: emp.data.getRange(0, 4).toList() );
List<Employe> e = [];
e.add(empx);
e.add(emp);
empData.value = e;
} else {
throw Exception('Failed to load emplo');
}
}
void deleteEmployee (String enumId){
debugPrint(empData.toString());
debugPrint("before");
int index = empData.indexWhere((ele) => ele.message == enumId);
empData[index].data.clear();
debugPrint("after");
debugPrint(empData.toString());
}
}
void main() {
runApp(const MyApp());
}
final EmployeeController employeeController = Get.put(EmployeeController());
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> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Obx(() => Row(
children: employeeController.empData
.map(
(e) => Expanded(
child: Column(
children: [
Text(e.message),
Text(e.toString()),
IconButton(
onPressed: () {
employeeController.deleteEmployee(e.message);
},
icon: Icon(Icons.abc_rounded),
)
],
),
),
)
.toList())),
);
}
}
In _MyHomePageState try to use employeeController.empData.value instead of employeeController.empData.
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Obx(() => Row(
children: employeeController.empData.value
.map(
(e) => Expanded(
child: Column(
children: [
Text(e.message),
Text(e.toString()),
IconButton(
onPressed: () {
employeeController.deleteEmployee(e.message);
},
icon: Icon(Icons.abc_rounded),
)
],
),
),
)
.toList())),
);
}
}

capture data from DropDownButton in flutter and send it to the database

I'm new to flutter app development and would like to ask for your help
I already learned to capture the data of a TextFormField but with the DropDownButtons I have no idea how it is I try to use controller to put a name but I get an error
I have a DropDownButton and it works for me, it is loading the list successfully and I would like to know, how to capture the data I select in the DropDownButton and send it to my database
This is the code that I am using:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _mySelection;
final String url = "http://webmyls.com/php/getdata.php";
List data = List();
Future<String> getSWData() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
data = resBody;
});
print(data);
return "Sucess";
}
#override
void initState() {
super.initState();
this.getSWData();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new DropdownButton(
//data != null,
isDense: true,
hint: new Text("Select"),
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['item_name']),
value: item['id'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection = newVal;
});
},
value: _mySelection,
),
),
);
}
}
I hope you can help me.
the latest dropdown value is always stores in your _mySelection. So the only thing you should do is to save _mySelection in your database.

Using Flutter and Dart, how can I get this Future to work?

I know that there are other ways of achieving this, but I want to use a Future via initState() to obtain a List using SharedPreferences. The following illustrates what I want to achieve, but it does not work as required, because the Future returns immediately before completing the task.
How should this be structured?
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _MyHomePageState extends State<MyHomePage> {
SharedPreferences _prefs;
String _sMessage = "No response from getting params";
List<String> _lsCategories;
#override
void initState() {
super.initState();
_initPreferences().then((_) {
try {
_lsCategories = _prefs.getStringList("categories") ?? [];
debugPrint("Categories = $_lsCategories");
_sMessage = "Categories loaded OK";
} catch (vError) {
_sMessage = ("Error loading categories = $vError");
}
setState(() {});
});
}
Future<void> _initPreferences() async {
SharedPreferences.getInstance().then((prefs) {
_prefs = prefs;
debugPrint("Preferences initialized OK");
}).catchError((vError) {
debugPrint("Error initializing preferences = ${vError.toString()}");
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_sMessage,
style: TextStyle(
color: Colors.red[500],
fontWeight: FontWeight.bold,
fontSize: 20)),
],
),
),
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Future Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: "Flutter Future Test"),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
Change your _initPreferences method to the following:
Future<void> _initPreferences() async {
try {
final prefs = await SharedPreferences.getInstance();
_prefs = prefs;
debugPrint("Preferences initialized OK");
} catch (e) {
debugPrint("Error initializing preferences = ${e.toString()}");
}
}
The issue is that when using .then() on a Future you are not waiting for that future to finish, using await does wait.
Try it.
Future<void> _initPreferences() async {
_prefs = await SharedPreferences.getInstance().catchError((vError) {
debugPrint("Error initializing preferences = ${vError.toString()}");
};
debugPrint("Preferences initialized OK");
}

How catch the opening and closing of the drawer in flutter?

How can I catch the opening and closing of the drawer in flutter? In principle, two objects must be are used for this purpose: DrawerController, which "holds" the drawer and the drawerCallback. drawerCallback should track the opening and closing of the drawer, but the code that is discussed at https://github.com/flutter/flutter/issues/21272 and https://github.com/flutter/flutter/issues/23630 does not works. Anyone can advise something?
Update 2021-12:
Scaffold(
drawer: DrawerWidget(),
onDrawerChanged: (isDrawerOpen) {
if(isDrawerOpen) {
//drawer is open
} else {
//drawer is close
}
},
body: bodyWidget(),
)
You can first refer to other people's replies on stackoverflow here
My solve:
get Drawer status on DrawerWidget
initState() : open drawer
dispose() : close drawer
Stream drawer status by DrawerService Provider
see full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
Provider(create: (_) => DrawerService()),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DrawerService _drawerService;
String drawerStatus = 'close';
#override
void initState() {
super.initState();
_drawerService = Provider.of(context, listen: false);
_listenDrawerService();
}
_listenDrawerService() {
_drawerService.status.listen((status) {
if(status) {
drawerStatus = 'open';
} else {
drawerStatus = 'close';
}
setState(() { });
});
}
#override
Widget build(BuildContext context) {
Color bgColor = Colors.yellow;
if(drawerStatus == 'open') {
bgColor = Colors.red;
}
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
drawer: DrawerWidget(),
body: Container(
decoration: BoxDecoration(color: bgColor),
height: 300,
child: Center(child: Text(drawerStatus),),
),
);
}
}
class DrawerWidget extends StatefulWidget {
#override
_DrawerWidgetState createState() => _DrawerWidgetState();
}
class _DrawerWidgetState extends State<DrawerWidget> {
DrawerService _drawerService;
#override
void initState() {
super.initState();
_drawerService = Provider.of(context, listen: false);
_drawerService.setIsOpenStatus(true);
}
#override
Widget build(BuildContext context) {
return Drawer(
child: Center(child: Text('drawer'),),
);
}
#override
void dispose() {
super.dispose();
_drawerService.setIsOpenStatus(false);
}
}
class DrawerService {
StreamController<bool> _statusController = StreamController.broadcast();
Stream<bool> get status => _statusController.stream;
setIsOpenStatus(bool openStatus) {
_statusController.add(openStatus);
}
}

How can my Flutter FutureBuilder change text at multiple places in my layout?

I read carefully the Flutter tutorial; Fetching data from internet: https://flutter.io/cookbook/networking/fetch-data/
My concern is that I want to update multiple texts in my layout.
The implementation only shows a way to update one:
FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
);
This works fine and displays one view at a time.
In Android Studio/Java, I would have done something like:
myTextView1.setText(snapshot.data.data1)
myTextView2.setText(snapshot.data.data2)
myTextView3.setText(snapshot.data.data3)
.....
myTextView10.setText(snapshot.data.data3)
But here in Flutter, I am currently limited to one "Widget" at a time.
Of course, I could provide my whole layout in the return argument, but that would be crazy!
Any idea/suggestion?
An alternative strategy is to have a local variable in the state class and update it when the future arrives. Thus, you can reference that variable wherever you need.
Here is an example:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Post _post = Post("Title 0", "Subtitle0 ", "description 0");
#override
void initState() {
super.initState();
_getPost();
}
void _getPost() async {
_post = await fetchPost();
setState(() {});
}
Future<Post> fetchPost() {
return Future.delayed(Duration(seconds: 4), () {
return Post("Title new", "Subtitle new", "description new");
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
new Text(_post.title),
new Text(_post.subtitle),
new Text(_post.description),
],
),
),
);
}
}
class Post {
final String title;
final String subtitle;
final String description;
Post(this.title, this.subtitle, this.description);
}
You can convert your request to Stream
import 'package:flutter/material.dart';
import 'package:random_pk/random_pk.dart';
import 'dart:async';
class TestWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(child: RandomContainer(
width: 200.0,
height: 200.0,
child: Center(child: _MyTextWidget(fetchPost().asStream())),
),),
);
}
Future<String> fetchPost() {
return Future.delayed(Duration(seconds: 4), () {
return "Title data";
});
}
}
class _MyTextWidget extends StatefulWidget {
_MyTextWidget(this.stream);
final Stream<String> stream;
#override
State<StatefulWidget> createState() => _MyTextWidgetState();
}
class _MyTextWidgetState extends State<_MyTextWidget> {
String text;
#override
void initState() {
widget.stream.listen((String data) {
setState(() {
text = data;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Text(text == null ? 'loading' : text);
}
}
In this example RandomContainer changes its color on every setState and it works as indicator, than changes are only in _MyTextWidget