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.
Related
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;
}
Anyone can help me with this, I'm trying to fetch data from a table in Supabase but it's showing error on the app screen.
I want to build an app that reads the data from Supabase without any authentication, only reading and displaying the data from the table, here I'm just testing before I start building my app.
a screenshot from the main page in the app
My code in main.dart
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Supabase.initialize(
url: '[https://bougcsiwnimbmnmvwjlb.supabase.co]',
anonKey: '[eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTY0Mzc5NzQyOCwiZXhwIjoxOTU5MzczNDI4fQ.Ac5s-ZOyUV-2rRoP_GUuPvdt7tGNocCSq-LU-ZtBVqQ]',
);
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.red,
),
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();
}
// SuPabase
class _MyHomePageState extends State<MyHomePage> {
Future<void> _getProfile(String name) async {
late final _usernameController ;
#override
Future<Widget> build(BuildContext context) async {
final response = await Supabase.instance.client
.from('channels')
.select()
.single()
.execute();
if (response.error != null && response.status != null) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(response.error!.message)));
}
if (response.data != null) {
_usernameController = response.data!['name'] as String;
}
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: ListView(
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
children: [
Text(_usernameController,
),
],
),
);
}
}
#override
Widget build(BuildContext context) {
throw UnimplementedError();
}
}
I really appetite if anyone can help in this.
I think I can spot few spots that you might want to fix.
First, you want to remove the [] around your Supabase URL and Supabase anon key like this.
await Supabase.initialize(
url: 'https://bougcsiwnimbmnmvwjlb.supabase.co',
anonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTY0Mzc5NzQyOCwiZXhwIjoxOTU5MzczNDI4fQ.Ac5s-ZOyUV-2rRoP_GUuPvdt7tGNocCSq-LU-ZtBVqQ',
);
Also, it seemed like you had some mismatch of brackets in your widget definition. I think this is along the line of what you wanted to do:
class _MyHomePageState extends State<MyHomePage> {
String? name;
Future<void> _getProfile() async {
final response = await Supabase.instance.client
.from('channels')
.select()
.single()
.execute();
if (response.error != null && response.status != null) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(response.error!.message)));
}
if (response.data != null) {
setState(() {
name = response.data!['name'] as String;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: ListView(
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
children: [
name == null ? const Text('loading') : Text(name!),
],
),
);
}
#override
void initState() {
_getProfile();
super.initState();
}
}
Good morning friends, I am trying to use DropdownButton, it brings me the information but it shows me an error before I bring the information.
I printed the data to verify that it did not come empty and it is effectively bringing the list without any problem
This is the error shown:
enter image description here
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;
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,
),
),
);
}
}
Yeimer Initialize data : List data = List(); your issue will be resolved.
Create this widget:
Widget _myDropDown() {
if (data == null) return Center();
return 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,
);
}
and then put _myDropDown inside your Center
I am new to flutter. I am having webview scaffold in the body section.
My objective is to scan the barcode (URL) and update the webview link. I could able to initialize webview scaffold, and scan the barcode and get the URL. when I update the set state, it did not update the webview. Any suggestion on this ?
import 'package:flutter/material.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _barcodedata ="";
String getcode ="";
String urllink ="https://www.google.com";
Future scanbarcode() async{
getcode = await FlutterBarcodeScanner.scanBarcode("#009922", "CANCEL", true, ScanMode.DEFAULT);
setState(() {
_barcodedata = getcode;
urllink =getcode;
});
print (getcode);
print(_barcodedata);
print(urllink);
print('Done1');
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Hello"),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.scanner),
onPressed: (){
scanbarcode();
},
)
],
),
body: WebviewScaffold(
url: urllink,
),
),
);
}
}
You can copy paste run full code below
I only remark some part of scan and return a fix url
you need FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
and use flutterWebviewPlugin.reloadUrl(urlString);
working demo
click scan button from flutter change to microsoft
full code
import 'package:flutter/material.dart';
//import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
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,
),
home: WebViewExample(),
);
}
}
class WebViewExample extends StatefulWidget {
#override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
TextEditingController controller = TextEditingController();
FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
var urlString = "https://google.com";
launchUrl() {
setState(() {
urlString = controller.text;
flutterWebviewPlugin.reloadUrl(urlString);
});
}
Future scanbarcode() async{
/*getcode = await FlutterBarcodeScanner.scanBarcode("#009922", "CANCEL", true, ScanMode.DEFAULT);
setState(() {
_barcodedata = getcode;
urllink =getcode;
});
print (getcode);
print(_barcodedata);
print(urllink);
print('Done1');*/
urlString = "https://www.microsoft.com";
flutterWebviewPlugin.reloadUrl(urlString);
}
#override
void initState() {
super.initState();
flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {
print(wvs.type);
});
}
#override
Widget build(BuildContext context) {
return WebviewScaffold(
appBar: AppBar(
title: Text("Hello"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.scanner),
onPressed: () => scanbarcode(),
)
],
),
url: urlString,
withZoom: false,
);
}
}
I would like to scroll through a drop-down list as part of a flutter driver test, however I can't seem to figure out exactly how I would do this?
I've tried using a ValueKey, and have tried digging through the Flutter Inspector in Intellij as well, but have had no luck thus far.
I have tried find.byType(Scrollable); and it doesn't seem to work even after widgetTester.tap(). Turns out I need to wait for the screen to update with widgetTester.pumpAndSettle()
testWidgets("Test DropdownButton", (WidgetTester widgetTester) async {
await widgetTester.pumpWidget(MyApp())
final dropdownButtonFinder = find.byKey(const ValueKey('DropdownButton')); final dropdownItemFinder = find.widgetWithText(InkWell, 'Item 50'); // find.textContaining() doesn't seem to work
// Tap on the DropdownButton
await widgetTester.tap(dropdownButtonFinder);
await widgetTester.pumpAndSettle(const Duration(seconds: 2));
final dropdownListFinder = find.byType(Scrollable);
expect(dropdownListFinder, findsOneWidget); // Finds Scrollable from tapping DropDownButton
// Scroll until the item to be found appears.
await widgetTester.scrollUntilVisible(dropdownItemFinder, 500.0,
scrollable: dropdownListFinder);
await widgetTester.tap(dropdownItemFinder);
await widgetTester.pumpAndSettle(const Duration(seconds: 2));
// Verify that the item contains the correct text.
expect(find.textContaining('Item 50'), findsOneWidget);
});
Main code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> mockList() => List<String>.generate(100, (i) => 'Item $i');
String? dropdownValue;
#override
Widget build(BuildContext context) {
// debugPrint('${foo!}');
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
key: Key('Widget1'),
),
body: Center(
child: DropdownButton(
key: Key('DropdownButton'),
value: dropdownValue,
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: mockList()
.map<DropdownMenuItem<String>>(
(String value) => DropdownMenuItem<String>(
value: value,
child: Text(value),
key: Key('item$value'),
),
)
.toList(),
)
);
}
}
Running the test