Failed host lookup from rest.coinapi.io - flutter

I am trying to fetch network data from the coinAPI to get the exchange rate for 1btc to usd.. but after fetching the api and awaiting it in price screen so the ui will give the exchange rate... I get failed host lookup
This is the coin_data.dart file... contains the api and networking
import 'dart:convert';
import 'package:http/http.dart' as http;
const List<String> currenciesList = [
'AUD',
'BRL',
'CAD',
'CNY',
'EUR',
'GBP',
'HKD',
'IDR',
'ILS',
'INR',
'JPY',
'MXN',
'NOK',
'NZD',
'PLN',
'RON',
'RUB',
'SEK',
'SGD',
'USD',
'ZAR'
];
const List<String> cryptoList = [
'BTC',
'ETH',
'LTC',
];
const coinAPIUrl = 'https://rest.coinapi.io/v1/exchangerate';
const apiKey = 'APIKEY';
class CoinData {
Future<dynamic> getCoinData() async {
// http.Response response = await http.get(Uri.parse('$coinAPIUrl/BTC/USD?apikey=$apiKey'));
http.Response response = await http.get(Uri.parse('$coinAPIUrl/BTC/USD?apikey=$apiKey'));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
var lastPrice = decodedData['rate'];
return lastPrice;
} else {
print(response.statusCode);
throw 'Problem with the get request';
}
}
}
This is the price_screen.dart file.. the actual UI and display of the exchange rate
import 'dart:io' show Platform;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ticker_bitcoin/coin_data.dart';
class PriceScreen extends StatefulWidget {
const PriceScreen({super.key});
#override
State<PriceScreen> createState() => _PriceScreenState();
}
class _PriceScreenState extends State<PriceScreen> {
late String selectedCurrency = 'USD';
DropdownButton<String> androidDropdown() {
List<DropdownMenuItem<String>> dropdownItems = [];
for (int i = 0; i < currenciesList.length; i++) {
String currency = currenciesList[i];
var newItem = DropdownMenuItem(
value: currency,
child: Text(currency),
);
dropdownItems.add(newItem);
}
return DropdownButton(
value: selectedCurrency,
items: dropdownItems,
onChanged: (value) {
setState(() {
selectedCurrency = value!;
});
},
);
}
CupertinoPicker iOSPicker() {
List<Text> pickerItems = [];
for (String currency in currenciesList) {
Text(currency);
pickerItems.add(Text(currency));
}
return CupertinoPicker(
itemExtent: 32.0,
onSelectedItemChanged: (selectedIndex) {
print(selectedIndex);
},
children: pickerItems,
);
}
// Widget getPicker() {
// if (Platform.isIOS) {
// return iOSPicker();
// } else if (Platform.isAndroid) {
// return androidDropdown();
// }
// return getPicker();
// }
String bitcoinValueInUSD = '?';
void getData() async {
try {
double data = await CoinData().getCoinData();
setState(() {
bitcoinValueInUSD = data.toStringAsFixed(0);
});
} catch (e) {
print(e);
}
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('๐Ÿค‘ Coin Ticker'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
child: Card(
color: Colors.lightBlueAccent,
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 28.0),
child: Text(
'1 BTC = $bitcoinValueInUSD USD',
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
),
),
),
Container(
height: 125.0,
alignment: Alignment.center,
padding: const EdgeInsets.only(bottom: 30.0),
color: Colors.lightBlue,
child: Platform.isIOS ? iOSPicker() : androidDropdown(),
),
],
),
);
}
}

It means your device/emulator got disconnected to the internet. If your host is connected to internet but emulator is disconnected then a cold reboot will do the trick. You'll find that under Device Manager > vertical ellipsis (โ‹ฎ) > Cold Boot Now button.

Related

I want to filter using CheckboxListTile in flutter but i have not showing any reflection of filtering in listview when i use Alert dialog?

I filter the one litview builder list to another checkbox list and this is working, but when i add this CheckboxListTile in Alert dialog when no filter reflection showing.
I used StatefulBuilder also but is not useful to filtering listview.
[This is first link to show Product list data][1]
This is second link of filter list
I am stuck in how to one data filter to another item filter that availiable in Alert dialog.
This is Api link
const String baseUrl = "https://run.mocky.io/v3/";
const String productDataUrl = baseUrl + "4ecbd2ea-a725-438b-b8fc-da8fc08bc875";
const String productCategoryDataUrl =
baseUrl + "0595387e-732e-47cf-9675-244fed9fc014";
This is product model class that listview model that we want to filter
class ProductDataModel {
int? productId;
String? productName;
int? productPrice;
int? productKG;
String? productCategoryId;
ProductDataModel(
{this.productId,
this.productName,
this.productPrice,
this.productKG,
this.productCategoryId});
ProductDataModel.fromJson(Map<String, dynamic> json) {
productId = json['ProductId'];
productName = json['ProductName'];
productPrice = json['ProductPrice'];
productKG = json['ProductKG'];
productCategoryId = json['ProductCategoryId'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ProductId'] = this.productId;
data['ProductName'] = this.productName;
data['ProductPrice'] = this.productPrice;
data['ProductKG'] = this.productKG;
data['ProductCategoryId'] = this.productCategoryId;
return data;
}
}
This ProductCategory Model class for using filter and this model class
data in CheckboxTile
class ProductCategoryDataModel {
int? productCategoryId;
String? productCategoryName;
bool? isChecked=false;
ProductCategoryDataModel(
{this.productCategoryId, this.productCategoryName, this.isChecked});
ProductCategoryDataModel.fromJson(Map<String, dynamic> json) {
productCategoryId = json['ProductCategoryId'];
productCategoryName = json['ProductCategoryName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ProductCategoryId'] = this.productCategoryId;
data['ProductCategoryName'] = this.productCategoryName;
return data;
}
}
This is code of showing listview and filter data using
checkboxlisttile that data in Alert dialog .
import 'dart:convert';
import 'dart:developer';
import 'package:dummy_checkbox_filter_list/commons/api_url.dart';
import 'package:dummy_checkbox_filter_list/model/product_category_data_model.dart';
import 'package:dummy_checkbox_filter_list/model/product_data_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<ProductDataModel> productDataList = [];
Set<ProductDataModel> productDataListDisplay = {};
List<ProductCategoryDataModel> productCategoryDataList = [];
List<ProductCategoryDataModel> selectProductCategoryDataList = [];
ScrollController scrollController = ScrollController();
bool isShowLoader = false;
getProductList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=> ${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productDataList.add(ProductDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
getProductCategoryList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productCategoryDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=>${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productCategoryDataList
.add(new ProductCategoryDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productCategoryDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
#override
void initState() {
getProductList();
getProductCategoryList();
super.initState();
}
#override
Widget build(BuildContext context) {
filterProduct(productDataList);
return Scaffold(
body: SafeArea(
child: isShowLoader == false
? SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
titlePadding: EdgeInsets.zero,
backgroundColor: Color(0xFF242424),
title: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: Icon(
Icons.close,
color: Colors.white,
size: 25,
))
],
),
contentPadding: EdgeInsets.zero,
content: Container(
padding: EdgeInsets.all(5),
width: double.maxFinite,
child: ListView(
padding: EdgeInsets.all(8.0),
children: [
Text(
"dfff "+productCategoryDataList[0].isChecked.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 16),
),
...productCategoryDataList
.map((e) => CheckboxListTile(
controlAffinity:
ListTileControlAffinity
.leading,
title: Text(
"${e.productCategoryName}",
style: TextStyle(
color: Colors.white,
fontSize: 16),
),
value: e.isChecked,
selected:
selectProductCategoryDataList
.contains(e),
onChanged: (val) {
print("val: "+val.toString());
setState(() {
e.isChecked = val;
selectProductCategoryDataList
.contains(e)
? selectProductCategoryDataList
.remove(e)
: selectProductCategoryDataList
.add(e);
print(
"_isChecked: ${e.isChecked}");
});
},
))
],
),
),
);
},
);
});
},
style: ElevatedButton.styleFrom(
primary: Colors.black,
onPrimary: Colors.white,
minimumSize: Size(
MediaQuery.of(context).size.width * 0.30,
MediaQuery.of(context).size.height * 0.05)),
child: Text(
"Filter",
style: TextStyle(fontSize: 15),
),
),
Container(
child: ListView.builder(
itemCount: productDataListDisplay.length,
shrinkWrap: true,
controller: scrollController,
itemBuilder: (context, index) {
return Card(
child: Container(
padding: EdgeInsets.only(top: 15, bottom: 15),
color: (index % 2 == 0)
? Colors.grey.shade100
: Colors.white,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(productDataListDisplay
.elementAt(index)
.productId
.toString()),
Center(
child: Text(
productDataListDisplay
.elementAt(index)
.productName
.toString(),
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productKG.toString()} KG",
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
),
),
],
),
),
);
},
),
),
],
),
)
: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
),
),
);
}
void filterProduct(allProducts) {
productDataListDisplay.clear();
if (selectProductCategoryDataList != null &&
selectProductCategoryDataList.isNotEmpty) {
final List<int> idsOfSelectedCategories = selectProductCategoryDataList
.map((category) => category.productCategoryId!)
.toList();
print("idsOfSelectedCategories=> $idsOfSelectedCategories");
Set<ProductDataModel> storesInSelectedCategories =
getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
setState(() {
productDataListDisplay.addAll(storesInSelectedCategories);
print(allProducts.length);
print(storesInSelectedCategories.length);
});
} else {
setState(() {
productDataListDisplay.addAll(allProducts);
});
}
}
Set<ProductDataModel> getStoresFromSelectedCategories(
List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
Set<ProductDataModel> allProductsFromCategory = {};
for (var categoryId in idsOfSelectedCategories) {
var productMatched = allProducts
.where((store) => store.productCategoryId!
.split(" ")
.contains(categoryId.toString()))
.toList();
print("Stores Matched runtime=>${productMatched.runtimeType}");
allProductsFromCategory.addAll(productMatched);
}
return allProductsFromCategory;
}
}
Add .then((value) {if (mounted) {setState(() {});}}); to showdialog so that state gets refreshed when alertdialog closes.
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<ProductDataModel> productDataList = [];
Set<ProductDataModel> productDataListDisplay = {};
List<ProductCategoryDataModel> productCategoryDataList = [];
List<ProductCategoryDataModel> selectProductCategoryDataList = [];
ScrollController scrollController = ScrollController();
bool isShowLoader = false;
getProductList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=> ${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productDataList.add(ProductDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
getProductCategoryList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productCategoryDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=>${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productCategoryDataList
.add(new ProductCategoryDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productCategoryDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
#override
void initState() {
getProductList();
getProductCategoryList();
super.initState();
}
#override
Widget build(BuildContext context) {
filterProduct(productDataList);
return Scaffold(
body: SafeArea(
child: isShowLoader == false
? SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
titlePadding: EdgeInsets.zero,
backgroundColor: const Color(0xFF242424),
title: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(
Icons.close,
color: Colors.white,
size: 25,
))
],
),
contentPadding: EdgeInsets.zero,
content: Container(
padding: EdgeInsets.all(5),
width: double.maxFinite,
child: ListView(
padding: EdgeInsets.all(8.0),
children: [
Text(
"dfff ${productCategoryDataList[0].isChecked}",
style: const TextStyle(
color: Colors.white,
fontSize: 16),
),
...productCategoryDataList
.map((e) => CheckboxListTile(
controlAffinity:
ListTileControlAffinity
.leading,
title: Text(
"${e.productCategoryName}",
style: const TextStyle(
color: Colors.white,
fontSize: 16),
),
value: e.isChecked,
selected:
selectProductCategoryDataList
.contains(e),
onChanged: (val) {
print("val: $val");
setState(() {
e.isChecked = val;
selectProductCategoryDataList
.contains(e)
? selectProductCategoryDataList
.remove(e)
: selectProductCategoryDataList
.add(e);
print(
"_isChecked: ${e.isChecked}");
});
},
))
],
),
),
);
},
);
}).then((value) {
if (mounted) {
setState(() {});
}
});
},
style: ElevatedButton.styleFrom(
primary: Colors.black,
onPrimary: Colors.white,
minimumSize: Size(
MediaQuery.of(context).size.width * 0.30,
MediaQuery.of(context).size.height * 0.05)),
child: const Text(
"Filter",
style: TextStyle(fontSize: 15),
),
),
Container(
child: ListView.builder(
itemCount: productDataListDisplay.length,
shrinkWrap: true,
controller: scrollController,
itemBuilder: (context, index) {
return Card(
child: Container(
padding: EdgeInsets.only(top: 15, bottom: 15),
color: (index % 2 == 0)
? Colors.grey.shade100
: Colors.white,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(productDataListDisplay
.elementAt(index)
.productId
.toString()),
Center(
child: Text(
productDataListDisplay
.elementAt(index)
.productName
.toString(),
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productKG.toString()} KG",
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
),
),
],
),
),
);
},
),
),
],
),
)
: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
),
),
);
}
void filterProduct(allProducts) {
productDataListDisplay.clear();
if (selectProductCategoryDataList != null &&
selectProductCategoryDataList.isNotEmpty) {
final List<int> idsOfSelectedCategories = selectProductCategoryDataList
.map((category) => category.productCategoryId!)
.toList();
print("idsOfSelectedCategories=> $idsOfSelectedCategories");
Set<ProductDataModel> storesInSelectedCategories =
getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
setState(() {
productDataListDisplay.addAll(storesInSelectedCategories);
print(allProducts.length);
print(storesInSelectedCategories.length);
});
} else {
setState(() {
productDataListDisplay.addAll(allProducts);
});
}
}
Set<ProductDataModel> getStoresFromSelectedCategories(
List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
Set<ProductDataModel> allProductsFromCategory = {};
for (var categoryId in idsOfSelectedCategories) {
var productMatched = allProducts
.where((store) => store.productCategoryId!
.split(" ")
.contains(categoryId.toString()))
.toList();
print("Stores Matched runtime=>${productMatched.runtimeType}");
allProductsFromCategory.addAll(productMatched);
}
return allProductsFromCategory;
}
}

how to build sorted listview in flutter (sort as per dates)

I want to display a listview from database. The notes stored in 'note' table are displayed successully. I want to display it as per the dates. i.e recent ones at the top and later ones(future ones) below them. if the date is of tomorrow then it should be at the top and day after tomorrow one below it. If the dates are same I want to sort them as per priority. Can anyone please help me.
(If u use any other date and time picker which can accept date and time together would also be helpful). In my case the table calendar only accepts the date. I am storing the date as TEXT(i dont know if its right)
new_note.dart// this is where I add a new note to the database.
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'package:intl/intl.dart';
import 'package:vers2cts/models/color_dropdown.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/form_helper.dart';
class NewNote extends StatefulWidget{
final NoteModel note;
final CustomerModel customer;
NewNote(this.customer,this. note);
#override
State<StatefulWidget> createState() {
return New_NoteState(this.customer,this.note);
}
}
class New_NoteState extends State<NewNote> with SingleTickerProviderStateMixin{
New_NoteState(this.customer,this.note);
NoteModel note=new NoteModel();
CustomerModel customer=new CustomerModel();
TextEditingController NoteController=TextEditingController();
TextEditingController custfNameController = TextEditingController();
DateTime _reminderDate = DateTime.now();
DateTime _selectedDay = DateTime.now();
DBService dbService=new DBService();
double _height;
double _width;
dynamic currentTime = DateFormat.jm().format(DateTime.now());
String _setTime, _setDate;
String _hour, _minute, _time;
String dateTime;
DateTime selectedDate = DateTime.now();
TimeOfDay selectedTime = TimeOfDay(hour: 00, minute: 00);
TextEditingController _dateController = TextEditingController();
TextEditingController _timeController = TextEditingController();
SpeedDial _speedDial(){
return SpeedDial(
animatedIcon: AnimatedIcons.add_event,
animatedIconTheme: IconThemeData(size: 24.0),
backgroundColor: Colors.yellow,
curve: Curves.easeInCirc,
children: [
SpeedDialChild(
child: Icon(Icons.location_on,color: Colors.yellow,),
label: 'Add Location',
),
SpeedDialChild(
child: Icon(Icons.keyboard_voice),
label: 'Add voice',
),
SpeedDialChild(
child: Icon(Icons.attachment_outlined,color :Colors.redAccent),
label: 'Add File',
),
SpeedDialChild(
child: Icon(Icons.image,color: Colors.lightBlue,),
label: 'Add Image',
),
],
);
}
//for Switch
bool isSwitched = false;
var textValue = 'Switch is OFF';
void toggleSwitch(bool value) {
if(isSwitched == false)
{
setState(() {
isSwitched = true;
note.rmnd_ind=1;
});
}
else
{
setState(() {
isSwitched = false;
note.rmnd_ind=0;
});
}
}
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if (picked != null)
setState(() {
selectedTime = picked;
_hour = selectedTime.hour.toString();
_minute = selectedTime.minute.toString();
_time = _hour + ' : ' + _minute;
_timeController.text = _time;
});
}
#override
void initState() {
_timeController.text=currentTime;
super.initState();
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
var name=customer.first_name+" "+customer.last_name;
custfNameController.text = name;
String _chosenValue;
return WillPopScope(
onWillPop: () {navigationBar
moveToLastScreen();
},
child: Scaffold(
appBar:AppBar(),
body:ListView(
children: <Widget>[
SizedBox(
height: 2.0,
),
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Align(
alignment: Alignment.centerLeft,
child: Text("Add New",textAlign: TextAlign.left,
style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
),
SizedBox(
height: 2.0,
),
Divider(),
SizedBox(
height: 2.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: NoteController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(width: 2.0),)),
keyboardType: TextInputType.multiline,
minLines: 5,//Normal textInputField will be displayed
maxLines: 5, // when user presses enter it will adapt to it
onChanged: (value) {
this.note.note = value;
},
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: TableCalendar(
selectedDayPredicate: (day) {
return isSameDay(_selectedDay, day);
},
onDaySelected: (selectedDay, focusedDay) {
setState(() {
_selectedDay=selectedDay;
String _reminderDate = DateFormat('dd-MM-yyyy').format(_selectedDay);
note.actn_on=_reminderDate.toString();
});
},// Set initial date
focusedDay: DateTime.now(),
firstDay: DateTime.utc(2010, 10, 16),
lastDay: DateTime.utc(2030, 3, 14),),
),
Row(
children: <Widget>[
Expanded(child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text("Set time",style: TextStyle(fontSize: 20),),
)),
Expanded(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: InkWell(
onTap: () {
_selectTime(context);
},
child: TextFormField(
style: TextStyle(fontSize: 30),
textAlign: TextAlign.center,
onSaved: (String val) {
_setTime = val;
},
enabled: false,
keyboardType: TextInputType.text,
controller: _timeController,
),
),
),
),
]
),
SizedBox(
height: height*0.03,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
children: <Widget>[
Text("Remind me",style: TextStyle(fontSize: 20),),
Padding(
padding: const EdgeInsets.only(left:80.0),
child: Container(
child: Switch(
onChanged: toggleSwitch,
value: isSwitched,
),
),
),
],),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(mainAxisAlignment: MainAxisAlignment.start,
children:<Widget>[
Text("Priority",style: TextStyle(fontSize: 20.0),),
Padding(
padding: const EdgeInsets.only(left:20.0),
child: Container(
child: SmoothStarRating(
size: height=50.0,
allowHalfRating: false,
onRated: (value) {
this.note.prty=value;
print("rating value -> $value");
},
),
),
)]),
),
SizedBox(
height: height*0.08,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme.of(context).primaryColorDark,
textColor: Colors.white,
child: Text('Save',textScaleFactor: 1.5,),
onPressed: (){
setState(() {
_save();
});
},
),
),
),
],
),
floatingActionButton:_speedDial(),
));
}
void moveToLastScreen() {
Navigator.pop(context, true);
}
void _save() async {
moveToLastScreen();
note.cust_id=customer.cust_id;
print(customer.cust_id);
print(note.cust_id);
int result;
if (note.note_id != null) { // Case 1: Update operation
result = await dbService.updateNote(note);
} else {
result = await dbService.insertNote(note);
}
if (result != 0) {
FormHelper.showAlertDialog(context,'Status', 'Note Saved Successfully');
} else {
FormHelper.showAlertDialog(context,'Status', 'Problem Saving Note');
}
}
}
note_info.dart // This is the screen which displays the listview
import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:vers2cts/utils/form_helper.dart';
import 'new_note.dart';
class Note_Info extends StatefulWidget{
final String appBarTitle;
final CustomerModel customer;
Note_Info(this. customer, this.appBarTitle);
#override
State<StatefulWidget> createState() {
return Note_InfoState(this. customer,this.appBarTitle);
}
}
class Note_InfoState extends State<Note_Info> {
DBService dbService = DBService();
List<NoteModel> noteList;
int count = 0;
static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
NoteModel note=NoteModel();
String appBarTitle;
CustomerModel customer=new CustomerModel();
Note_InfoState(this.customer, this.appBarTitle);
bool rememberMe = false;
DateTime _date = DateTime.now();
TextEditingController custfNameController = TextEditingController();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
updateListView();
if (noteList == null) {
noteList = List<NoteModel>();
updateListView();
}
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
var height = MediaQuery.of(context).size.height;
var name=customer.first_name+" "+customer.last_name;
custfNameController.text = name;
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.add,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => NewNote(customer,note)));
},
)
],
),
body: Container(
child: Column(
children: <Widget>[
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(children: [
ImageProfile(customer.cust_photo),
Padding(
padding: const EdgeInsets.only(left: 30.0),
child: IconButton(
icon: Icon(
Icons.call,
color: Colors.green,
size: 45,
),
onPressed: () {
},
),
),
],),
),
SizedBox(
height: 50,
child: AppBar(
bottom: TabBar(
tabs: [
Tab(
text: "All",
),
Tab(
text: "Pending",
),
Tab(
text: "Cancelled",
),
Tab(
text: "Completed",
),
],
),
),
),
// create widgets for each tab bar here
Expanded(
child: TabBarView(
children: [
// first tab bar view widget
Container(
child: getNotecheckList()
),
// second tab bar viiew widget
Container(
),
Container(
child: Center(
child: Text(
'Cancelled',
),
),
),
Container(
child: Center(
child: Text(
'Completed',
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme
.of(context)
.primaryColorDark,
textColor: Colors.white,
child: Text('Save', textScaleFactor: 1.5,),
onPressed: () {
setState(() {
//_reset();
});
},
),
),
),
]
),
)
));
}
Widget ImageProfile(String fileName) {
return Center(
child: CircleAvatar(
radius: 80.0,
backgroundImage: fileName == null
?AssetImage('images/person_icon.jpg')
:FileImage(File(customer.cust_photo))),
);
}
ListView getNoteListView() {
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
title: Text(this.noteList[position].note, style: titleStyle,),
//subtitle: Text(this.customerList[position].date),
trailing: GestureDetector(
child: Icon(Icons.delete, color: Colors.grey,),
onTap: () {
// _delete(context, customerList[position]);
},
),
onTap: () {
//navigateToDetail(this.customerList[position],'Edit ');
},
),
);
},
);
}
Future<void> updateListView() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
int cid=customer.cust_id;
Future<List<NoteModel>> noteListFuture = dbService.getCustomerNotes(cid);
noteListFuture.then((noteList) {
setState(() {
this.noteList = noteList;
this.count = noteList.length;
});
});
});
}
int _isChecked=-1;
var selectedIndices = [];
ListView getNotecheckList() {
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: CheckboxListTile(
title: Text(this.noteList[position].note),
subtitle: Text(this.noteList[position].actn_on),
value: selectedIndices.contains(position),
onChanged: (_) {
if (selectedIndices.contains(position)) {
selectedIndices.remove(position);// unselect
} else {
selectedIndices.add(position); // select
}
},
controlAffinity: ListTileControlAffinity.leading,
),
);
},
);
}
}
}
note_model.dart
import 'model.dart';
class NoteModel extends Model {
static String table = 'note';
bool isSelected=false;
int note_id;
int cust_id;
String note;
String actn_on;
int rmnd_ind;
double prty;
String colr;
String sts;
int id;
String cre_date;
String cre_by;
String mod_date;
String mod_by;
int txn_id;
int delete_ind;
NoteModel({
this.note_id,
this.cust_id,
this.note,
this.actn_on,
this.rmnd_ind,
this.prty,
this.colr,
this.sts,
this.id,
this.cre_date,
this.cre_by,
this.mod_date,
this.mod_by,
this.txn_id,
this.delete_ind
});
static NoteModel fromMap(Map<String, dynamic> map) {
return NoteModel(
note_id: map["note_id"],
cust_id: map['cust_id'],
note: map['note'].toString(),
actn_on: map['actn_on'].toString(),
rmnd_ind: map['rmnd_ind'],
prty: map['prty'],
colr: map['colr'].toString(),
sts: map['sts'].toString(),
id: map['id'],
cre_date: map['cre_date'].toString(),
cre_by: map['cre_by'].toString(),
mod_date: map['mod_date'].toString(),
mod_by: map['mod_by'].toString(),
txn_id: map['txn_id'],
delete_ind: map['delete_ind'],
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'note_id': note_id,
'cust_id': cust_id,
'note':note,
'actn_on': actn_on,
'rmnd_ind': rmnd_ind,
'prty': prty,
'colr': colr,
'sts':sts,
'id': id,
'cre_date': cre_date,
'cre_by': cre_by,
'mod_date':mod_date,
'mod_by':mod_by,
'txn_id':txn_id,
'delete_ind': delete_ind
};
if (note_id != null) {
map['note_id'] = note_id;
}
return map;
}
}
db_service.dart
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/utils/db_helper.dart';
class DBService {
Future<int> insertNote(NoteModel note) async {
await DB.init();
var result = await DB.insert(NoteModel.table, note);
return result;
}
Future<List<Map<String, dynamic>>> getNoteMapList() async {
await DB.init();
var result = await DB.query(NoteModel.table);
return result;
}
Future<List<NoteModel>> getCustomerNotes(int customer) async {
await DB.init();
var res = await DB.rawQuery("note WHERE cust_id = '$customer'");
int count = res.length;
List<NoteModel> notelist = List<NoteModel>();
for (int i = 0; i < count; i++) {
notelist.add(NoteModel.fromMap(res[i]));
}
return notelist;
}
}
db_helper.dart actn_on saves the date and prty saves the priority
import 'dart:async';
import 'package:vers2cts/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';
abstract class DB {
static Database _db;
static int get _version => 1;
static Future<Database> init() async {
if (_db != null) {
return _db;
}
try {
var databasesPath = await getDatabasesPath();
String _path = p.join(databasesPath, 'CTS.db');
_db = await openDatabase(_path, version: _version, onCreate: onCreate);
print('db location:'+_path);
} catch (ex) {
print(ex);
}
}
static void onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE note (note_id INTEGER PRIMARY KEY,cust_id INTEGER, '
'note TEXT, '
'actn_on TEXT, rmnd_ind INTEGER, prty REAL, colr TEXT,'
'sts TEXT,'
'id INTEGER, cre_date TEXT,cre_by TEXT, mod_date TEXT,mod_by TEXT, txn_id INTEGER, delete_ind INTEGER)');
}
static Future<List<Map<String, dynamic>>> query(String table) async =>
_db.query(table);
static Future<int> insert(String table, Model model) async =>
await _db.insert(table, model.toMap());
static Future<List<Map<String, dynamic>>> rawQuery(String table) async =>
_db.query(table);
}
Thankyou DarShan I got my answer I just had to use ORDER BY in my query
Future<List<NoteModel>> getCustomerNotes(int customer) async {
await DB.init();
var res = await DB.rawQuery("note WHERE cust_id = '$customer' ORDER BY actn_on ASC,prty DESC;");
int count = res.length;
List<NoteModel> notelist = List<NoteModel>();
// For loop to create a 'Note List' from a 'Map List'
for (int i = 0; i < count; i++) {
notelist.add(NoteModel.fromMap(res[i]));
}
return notelist;
}

How to select multiple checkboxes in flutter in checkboxlisttile

Can anyone please tell me how do I select multiple options in checkboxlisttile.
Here I am able to click only one option. I want to set the status column in note table in database as completed when i check the particular item.
(Actually I want to select the item as completed and display it under another tab called completed. checkboxlisttile is created dynamically i.e from database. When a new note is added it is displayed in this listview.)
note_info.dart //this is the screen where notes are displayed i.e listview
import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'new_note.dart';
class Note_Info extends StatefulWidget{
final String appBarTitle;
final CustomerModel customer;
//Note_Info();
Note_Info(this. customer, this.appBarTitle);
#override
State<StatefulWidget> createState() {
//return Note_InfoState();
return Note_InfoState(this. customer,this.appBarTitle);
}
}
class Note_InfoState extends State<Note_Info> {
DBService dbService = DBService();
List<NoteModel> noteList;
int count = 0;
static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
NoteModel note=NoteModel();
String appBarTitle;
CustomerModel customer=new CustomerModel();
Note_InfoState(this.customer, this.appBarTitle);
bool rememberMe = false;
DateTime _date = DateTime.now();
TextEditingController custfNameController = TextEditingController();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
updateListView();
if (noteList == null) {
noteList = List<NoteModel>();
updateListView();
}
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
var height = MediaQuery.of(context).size.height;
var name=customer.first_name+" "+customer.last_name;
custfNameController.text = name;
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.add,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => NewNote(customer,note)));
},
)
],
),
body: Container(
child: Column(
children: <Widget>[
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(children: [
ImageProfile(customer.cust_photo),
Padding(
padding: const EdgeInsets.only(left: 30.0),
child: IconButton(
icon: Icon(
Icons.call,
color: Colors.green,
size: 45,
),
onPressed: () {
},
),
),
],),
),
SizedBox(
height: 50,
child: AppBar(
bottom: TabBar(
tabs: [
Tab(
text: "All",
),
Tab(
text: "Pending",
),
Tab(
text: "Cancelled",
),
Tab(
text: "Completed",
),
],
),
),
),
// create widgets for each tab bar here
Expanded(
child: TabBarView(
children: [
// first tab bar view widget
Container(
child: getNotecheckList()
),
// second tab bar view widget
Container(
),
Container(
child: Center(
child: Text(
'Cancelled',
),
),
),
Container(
child: Center(
child: Text(
'Completed',
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme
.of(context)
.primaryColorDark,
textColor: Colors.white,
child: Text('Save', textScaleFactor: 1.5,),
onPressed: () {
setState(() {
//_reset();
});
},
),
),
),
]
),
)
));
}
Widget ImageProfile(String fileName) {
return Center(
child: CircleAvatar(
radius: 80.0,
backgroundImage: fileName == null
?AssetImage('images/person_icon.jpg')
:FileImage(File(customer.cust_photo))),
);
}
Future<void> updateListView() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
int cid=customer.cust_id;
Future<List<NoteModel>> noteListFuture = dbService.getCustomerNotes(cid);
noteListFuture.then((noteList) {
setState(() {
this.noteList = noteList;
this.count = noteList.length;
});
});
});
}
int _isChecked=-1;
ListView getNotecheckList() {
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: CheckboxListTile(
title: Text(this.noteList[position].note),
subtitle: Text(this.noteList[position].actn_on),
//secondary: const Icon(Icons.web),
value: position== _isChecked,
onChanged: (bool value) {
setState(() {
_isChecked = value?position:-1;
});
},
controlAffinity: ListTileControlAffinity.leading,
),
);
},
);
}
}
new_note.dart //this is where new note is added.
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'package:intl/intl.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/form_helper.dart';
class NewNote extends StatefulWidget{
final NoteModel note;
final CustomerModel customer;
NewNote(this.customer,this. note);
//Dropdown
/*
final String label;
final Function(Color) onChanged;
final double height;
final double width;
NewNote.fordropdwn({
Key key,
this.onChanged,
this.height = 25,
this.width = 150,
this.label,
}) : super(key: key);*/
#override
State<StatefulWidget> createState() {
//return New_NoteState(this.customer);
return New_NoteState(this.customer,this.note);
}
}
class New_NoteState extends State<NewNote> with SingleTickerProviderStateMixin{
New_NoteState(this.customer,this.note);
NoteModel note=new NoteModel();
CustomerModel customer=new CustomerModel();
TextEditingController NoteController=TextEditingController();
TextEditingController custfNameController = TextEditingController();
DateTime _reminderDate = DateTime.now();
DBService dbService=new DBService();
SpeedDial _speedDial(){
return SpeedDial(
// child: Icon(Icons.add),
animatedIcon: AnimatedIcons.add_event,
animatedIconTheme: IconThemeData(size: 24.0),
backgroundColor: Colors.yellow,
curve: Curves.easeInCirc,
children: [
SpeedDialChild(
child: Icon(Icons.location_on,color: Colors.yellow,),
//backgroundColor: Theme.of(context).primaryColor,
label: 'Add Location',
//labelBackgroundColor:Theme.of(context).primaryColor,
),
SpeedDialChild(
child: Icon(Icons.keyboard_voice),
//backgroundColor: Colors.yellow,
label: 'Add voice',
//labelBackgroundColor: Colors.yellow
),
SpeedDialChild(
child: Icon(Icons.attachment_outlined,color :Colors.redAccent),
//backgroundColor:Theme.of(context).primaryColorLight,
label: 'Add File',
// labelBackgroundColor: Theme.of(context).primaryColorLight
),
SpeedDialChild(
child: Icon(Icons.image,color: Colors.lightBlue,),
//backgroundColor: Colors.yellow,
label: 'Add Image',
// labelBackgroundColor: Colors.yellow,
),
],
);
}
//for DropDownMenu
Color value=Colors.red;
final List<Color> colors = [
Colors.red,
Colors.blue,
Colors.green,
Colors.yellow,
Colors.pink,
Colors.purple,
Colors.brown,
];
//for Switch
bool isSwitched = false;
var textValue = 'Switch is OFF';
void toggleSwitch(bool value) {
if(isSwitched == false)
{
setState(() {
isSwitched = true;
note.rmnd_ind=1;
//this.note.remindOn = _reminderDate.toString();
});
}
else
{
setState(() {
isSwitched = false;
note.rmnd_ind=0;
});
}
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
var name=customer.first_name+customer.last_name;
custfNameController.text = name;
return WillPopScope(
onWillPop: () {
// Write some code to control things, when user press Back navigation button in device navigationBar
moveToLastScreen();
},
child: Scaffold(
appBar:AppBar(),
body:ListView(
children: <Widget>[
SizedBox(
height: 2.0,
),
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Align(
alignment: Alignment.centerLeft,
child: Text("Add New",textAlign: TextAlign.left,
style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
),
SizedBox(
height: 2.0,
),
Divider(),
SizedBox(
height: 2.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: NoteController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(width: 2.0),)),
keyboardType: TextInputType.multiline,
minLines: 5,//Normal textInputField will be displayed
maxLines: 5, // when user presses enter it will adapt to it
onChanged: (value) {
this.note.note = value;
},
),
),
TableCalendar(
selectedDayPredicate: (day) {
return isSameDay(_reminderDate, day);
},
onDaySelected: (selectedDay, focusedDay) {
setState(() {
String _reminderDate = DateFormat('dd-MM-yyyy').format(selectedDay);
note.actn_on=_reminderDate.toString();
});
},// Set initial date
focusedDay: DateTime.now(),
firstDay: DateTime.utc(2010, 10, 16),
lastDay: DateTime.utc(2030, 3, 14),),
SizedBox(
height: height*0.03,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(//mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Remind me",style: TextStyle(fontSize: 20),),
Padding(
padding: const EdgeInsets.only(left:80.0),
child: Container(
child: Switch(
onChanged: toggleSwitch,
value: isSwitched,
//activeColor: Colors.blue,
//activeTrackColor: Colors.yellow,
//inactiveThumbColor: Colors.redAccent,
//inactiveTrackColor: Colors.orange,
),
),
),
],),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(mainAxisAlignment: MainAxisAlignment.start,
children:<Widget>[
Text("Priority",style: TextStyle(fontSize: 20.0),),
Padding(
padding: const EdgeInsets.only(left:20.0),
child: Container(
child: SmoothStarRating(
size: height=50.0,
allowHalfRating: false,
onRated: (value) {
this.note.prty=value;
print("rating value -> $value");
},
),
),
)]),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Color",style: TextStyle(fontSize: 20),),
Padding(
padding: const EdgeInsets.only(left:80.0),
child: Container(
child: DropdownButton<Color>(
value: value,
//hint: Text(widget.label ?? ''),
onChanged: (color) {
setState(() => value = color);
//widget.onChanged(color);
},
items: colors.map((e) => DropdownMenuItem(
value: e,
child: Container(
// width: 60.0,
//height: 10.0,
width: 60.0,
// height: widget.height,
color: e,
),
),
)
.toList(),
),
),
),
],),
),
SizedBox(
height: height*0.08,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme.of(context).primaryColorDark,
textColor: Colors.white,
child: Text('Save',textScaleFactor: 1.5,),
onPressed: (){
setState(() {
_save();
});
},
),
),
),
],
),
floatingActionButton:_speedDial(),
));
}
void moveToLastScreen() {
Navigator.pop(context, true);
}
void _save() async {
moveToLastScreen();
note.cust_id=customer.cust_id;
print(customer.cust_id);
print(note.cust_id);
int result;
if (note.note_id != null) { // Case 1: Update operation
result = await dbService.updateNote(note);
} else { // Case 2: Insert Operation
result = await dbService.insertNote(note);
}
if (result != 0) { // Success
FormHelper.showAlertDialog(context,'Status', 'Note Saved Successfully');
} else { // Failure
FormHelper.showAlertDialog(context,'Status', 'Problem Saving Note');
}
}
}
db_service.dart
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/languages_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/user_model.dart';
import 'package:vers2cts/utils/db_helper.dart';
class DBService {
Future<int> insertNote(NoteModel note) async {
await DB.init();
var result = await DB.insert(NoteModel.table, note);
return result;
}
Future<List<NoteModel>> getCustomerNotes(int customer) async {
await DB.init();
var res = await DB.rawQuery("note WHERE cust_id = '$customer'");
int count = res.length;
List<NoteModel> notelist = List<NoteModel>();
// For loop to create a 'Note List' from a 'Map List'
for (int i = 0; i < count; i++) {
notelist.add(NoteModel.fromMap(res[i]));
}
return notelist;
}
}
note_model.dart
import 'model.dart';
class NoteModel extends Model {
static String table = 'note';
bool isSelected=false;
int note_id;
int cust_id;
String note;
String actn_on;
int rmnd_ind;
double prty;
String colr;
String sts;
int id;
String cre_date;
String cre_by;
String mod_date;
String mod_by;
int txn_id;
int delete_ind;
NoteModel({
this.note_id,
this.cust_id,
this.note,
this.actn_on,
this.rmnd_ind,
this.prty,
this.colr,
this.sts,
this.id,
this.cre_date,
this.cre_by,
this.mod_date,
this.mod_by,
this.txn_id,
this.delete_ind
});
static NoteModel fromMap(Map<String, dynamic> map) {
return NoteModel(
note_id: map["note_id"],
cust_id: map['cust_id'],
note: map['note'].toString(),
actn_on: map['actn_on'].toString(),
rmnd_ind: map['rmnd_ind'],
prty: map['prty'],
colr: map['colr'].toString(),
sts: map['sts'].toString(),
id: map['id'],
cre_date: map['cre_date'].toString(),
cre_by: map['cre_by'].toString(),
mod_date: map['mod_date'].toString(),
mod_by: map['mod_by'].toString(),
txn_id: map['txn_id'],
delete_ind: map['delete_ind'],
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'note_id': note_id,
'cust_id': cust_id,
'note':note,
'actn_on': actn_on,
'rmnd_ind': rmnd_ind,
'prty': prty,
'colr': colr,
'sts':sts,
'id': id,
'cre_date': cre_date,
'cre_by': cre_by,
'mod_date':mod_date,
'mod_by':mod_by,
'txn_id':txn_id,
'delete_ind': delete_ind
};
if (note_id != null) {
map['note_id'] = note_id;
}
return map;
}
}
db_helper.dart
import 'dart:async';
import 'package:vers2cts/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';
abstract class DB {
static Database _db;
static int get _version => 1;
static Future<Database> init() async {
if (_db != null) {
return _db;
}
try {
var databasesPath = await getDatabasesPath();
String _path = p.join(databasesPath, 'CTS.db');
_db = await openDatabase(_path, version: _version, onCreate: onCreate);
print('db location:'+_path);
} catch (ex) {
print(ex);
}
}
static void onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE note (note_id INTEGER PRIMARY KEY,cust_id INTEGER, '
'note TEXT, '
'actn_on TEXT, rmnd_ind INTEGER, prty REAL, colr TEXT,'
'sts TEXT,'
'id INTEGER, cre_date TEXT,cre_by TEXT, mod_date TEXT,mod_by TEXT, txn_id INTEGER, delete_ind INTEGER)');
}
static Future<List<Map<String, dynamic>>> query(String table) async =>
_db.query(table);
static Future<int> insert(String table, Model model) async =>
await _db.insert(table, model.toMap());
static Future<Batch> batch() async => _db.batch();
static Future<List<Map<String, dynamic>>> rawQuery(String table) async =>
_db.query(table);
}
You need to store what all values are selected from user and then play with it.
For example -
var selectedIndexes = [];
ListView getNotecheckList() {
return ListView.builder(
itemCount: count,
itemBuilder: (_, int index) {
return Card(
color: Colors.white,
elevation: 2.0,
child: CheckboxListTile(
title: Text(this.noteList[position].note),
subtitle: Text(this.noteList[position].actn_on),
value: selectedIndexes.contains(index),
onChanged: (_) {
if (selectedIndexes.contains(index)) {
selectedIndexes.remove(index); // unselect
} else {
selectedIndexes.add(index); // select
}
},
controlAffinity: ListTileControlAffinity.leading,
),
);
},
);
}
store only index or whole array and play around
Output :-
Code :-
import 'package:flutter/material.dart';
class CheckBoxExample extends StatefulWidget {
const CheckBoxExample({Key? key}) : super(key: key);
#override
State<CheckBoxExample> createState() => _CheckBoxExampleState();
}
class _CheckBoxExampleState extends State<CheckBoxExample> {
List multipleSelected = [];
List checkListItems = [
{
"id": 0,
"value": false,
"title": "Sunday",
},
{
"id": 1,
"value": false,
"title": "Monday",
},
{
"id": 2,
"value": false,
"title": "Tuesday",
},
{
"id": 3,
"value": false,
"title": "Wednesday",
},
{
"id": 4,
"value": false,
"title": "Thursday",
},
{
"id": 5,
"value": false,
"title": "Friday",
},
{
"id": 6,
"value": false,
"title": "Saturday",
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: [
Column(
children: List.generate(
checkListItems.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
checkListItems[index]["title"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: checkListItems[index]["value"],
onChanged: (value) {
setState(() {
checkListItems[index]["value"] = value;
if (multipleSelected.contains(checkListItems[index])) {
multipleSelected.remove(checkListItems[index]);
} else {
multipleSelected.add(checkListItems[index]);
}
});
},
),
),
),
const SizedBox(height: 64.0),
Text(
multipleSelected.isEmpty ? "" : multipleSelected.toString(),
style: const TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}

I'd like to have https:// automatically attached to the link

When I tried to retrieve img from the website, the link started with /upload/.... instead of https://.
I want to have https:// written automatically in front of me. What should I do?
homepage:
<div class="photo_list">
<ul>
<li>
<a href="/yongwon-h/na/ntt/selectNttInfo.do?nttSn=85189591&mi=73747">
<img src="/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_85189591/thumb/thumb_img_9028b523-7bfb-466f-848c-65870a93b99c1616411595463.jpg" onerror="this.src='/images/co/na/noImg.gif'" alt="๋Œ€ํ‘œ์ด๋ฏธ์ง€">
<p>์ฑ…์„ ๊ฐ€๊นŒ์ด, ์ฑ…์€ ๋‚˜์˜ ์นœ๊ตฌ!! ์•„์นจ๋…์„œ์˜ ์ƒํ™œํ™”!!!</p>
<span>
2021.03.22
<br> ์กฐํšŒ 6
</span>
</a>
</li>
</ul>
</div>
MY CODE:
import 'package:flutter/material.dart';
import 'package:flutter_share/flutter_share.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:http/http.dart' as http;
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as parser;
import 'package:url_launcher/url_launcher.dart';
class UpdatePost extends StatefulWidget {
#override
_UpdatePostState createState() => _UpdatePostState();
}
class _UpdatePostState extends State<UpdatePost> {
List<String> title = List();
List<String> post = List();
List<String> link = List();
List<String> image = List();
void _getDataFromWeb() async {
Uri uri = Uri.parse(
'http://yongwon-h.gne.go.kr/yongwon-h/na/ntt/selectNttList.do?mi=73747&&bbsId=62865');
final response = await http.get(uri);
dom.Document document = parser.parse(response.body);
final link2 = document.getElementsByClassName('photo_list');
final content = document.getElementsByClassName('photo_list');
final elements = document.getElementsByClassName('photo_list');
final ImageElement = document.getElementsByClassName('photo_list');
setState(() {
title = elements
.map((element) => element.getElementsByTagName("p")[0].innerHtml)
.toList();
post = content
.map((element) => element.getElementsByTagName("span")[0].innerHtml)
.toList();
link = link2
.map((element) =>
element.getElementsByTagName("a")[0].attributes['href'])
.toList();
image = ImageElement.map((element) =>
element.getElementsByTagName("img")[0].attributes['src']).toList();
});
}
Future<void> share(dynamic link, String title) async {
await FlutterShare.share(
title: 'Codding Application',
text: title,
linkUrl: link,
chooserTitle: 'Where You Want to Share');
}
#override
void initState() {
_getDataFromWeb();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black87,
body: post.length == 0
? Text("No data", style: TextStyle(color: Colors.white))
: ListView.builder(
itemCount: post.length,
itemBuilder: (context, index) {
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 375),
child: SlideAnimation(
child: FadeInAnimation(
child: GestureDetector(
onTap: () async {
dynamic url = link[index];
if (await canLaunch(url))
launch(url);
else {
print('error');
}
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Card(
child: Container(
color: Colors.black87,
child: Column(
children: <Widget>[
Container(
child: Image.network(
image[index],
scale: 0.1,
),
),
Align(
alignment: Alignment.centerLeft,
child: Text(
title[index],
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
fontSize: 20,
),
),
),
SizedBox(height: 15),
Text(
post[index],
style: TextStyle(
color: Colors.white,
),
),
Row(
children: <Widget>[
FlatButton(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(5.0),
side: BorderSide(color: Colors.white)),
onPressed: () {
share(link[index], title[index]);
},
child: Text(
"Share With Friends",
style: TextStyle(
color: Colors.red,
),
),
),
SizedBox(width: 10),
FlatButton(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(5.0),
side: BorderSide(color: Colors.white)),
onPressed: () async {
dynamic url = link[index];
if (await canLaunch(url))
launch(url);
else {
print('error');
}
},
child: Text(
"Explore Post",
style: TextStyle(
color: Colors.red,
),
),
),
],
),
],
),
),
),
),
))),
);
},
),
);
}
}
conclusion:
I want to automatically put http://yongwon-h.gne.go.kr in front of the called tag a.
I feel like I'm asking repeatedly, but I really don't know. I googled thousands of sites in a week. Please help me.
import 'dart:async';
import 'package:wnetworking/wnetworking.dart';
final Map<String, Map<String, dynamic>> reDic = {
'notices' : {
'relPath' : '/yongwon-h/main.do',
're' : <RegExp>[
RegExp(r'<h2 class="tit_1">(.|\n|\r|\u2028|\u2029)*?<h2 class="tit_2">'),
RegExp(r'<li><a.+>(.+)<\/a>(.|\n|\r|\u2028|\u2029)*?(\d{4}\.\d\d\.\d\d)'),
]
},
'images' : {
'relPath' : '/yongwon-h/na/ntt/selectNttList.do?mi=73747&&bbsId=62865',
're' : <RegExp>[
RegExp(r'<div class="photo_list">(.|\n|\r|\u2028|\u2029)*?<!-- \/\/๊ฒŒ์‹œํŒ ๋ฆฌ์ŠคํŠธ'),
RegExp(r'<img src="(.+)" onerror'),
]
},
};
class Yongwon {
static const _baseUrl = 'http://yongwon-h.gne.go.kr';
static FutureOr<void> fetchNoticies() async {
await _getHTMLObjects(
reDic['notices']!['relPath'],
reDic['notices']!['re']![0],
reDic['notices']!['re']![1],
)
.then((matches) {
if (matches != null) {
matches.forEach((match) => print('${match.group(1)} ..... ${match.group(3)}'));
}
});
}
static FutureOr<void> fetchImages() async {
await _getHTMLObjects(
reDic['images']!['relPath'],
reDic['images']!['re']![0],
reDic['images']!['re']![1],
)
.then((matches) {
if (matches != null) {
matches.forEach((match) => print('$_baseUrl${match.group(1)}'));
}
});
}
static Future<Iterable<RegExpMatch>?> _getHTMLObjects(String relPath, RegExp reContainer, RegExp reObjects) async {
var page = await NetService.getRaw(_baseUrl + relPath)
.whenComplete(() => print('Page done.\n'));
if (page != null) {
final objectsPane = reContainer.firstMatch(page)!.group(0);
if (objectsPane != null) {
return Future.value(reObjects.allMatches(objectsPane));
}
}
return null;
}
}
void main(List<String> args) async {
await Yongwon.fetchImages();
print('\nJob done!');
}
Netservice (partial code):
class NetService {
static Future<String?> getRaw(String url, {int okCode = 200}) {
return http.get(Uri.parse(url))
.then((response) {
if (response.statusCode == okCode) {
return response.body;
}
PrintService.showDataNotOK(response);
return null;
})
.catchError((err) => PrintService.showError(err));
}
}
Result:
Page done.
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_85189591/thumb/thumb_img_9028b523-7bfb-466f-848c-65870a93b99c1616411595463.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_85169237/thumb/thumb_img_0fe7d01b-6941-4468-8623-088af971fbf21616047569744.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_85148970/thumb/thumb_img_67ae1c34-cd49-4af4-8a68-cacec672c84d1615859096270.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_85041266/thumb/thumb_img_ddc5097b-ae4e-4190-b0b8-1aa88cf78e491614223854604.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_85039068/thumb/thumb_img_f5c77ec4-a448-44b0-b5b1-61079be18eb61614145925749.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_85002051/thumb/thumb_img_0df44e4d-9872-4605-a94f-32b3004bc42a1612331543446.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_84955511/thumb/thumb_img_de1fc864-2689-4917-85bc-b5d714040b1f1610248949513.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_84950100/thumb/thumb_img_cd3270ee-7bd0-4601-81fc-2de446903e281609919353000.jpg
http://yongwon-h.gne.go.kr/upload/bbs/files/2021/hgschl/yongwon-h/ntt/62865/ntt_84950096/thumb/thumb_img_0eee718a-a2de-4182-a0d9-f97de17d98741609919173296.jpg
Job done!

Flutter - setState isn't working inside http response code

I am having a simple page to fetch data from server and parsing the response.
I am having two widgets that are visible to user, one is the _loadingWidget() widget another one is the errorWidget() widget.
I have added some print statements for showing up to where code is being executed. Everything is working fine but setState for errorWidget() is not working.
What i'm doing wrong here?
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:validators/validators.dart';
import '../strings.dart';
class FetchDataPage extends StatefulWidget {
final String text;
FetchDataPage({Key key, #required this.text}) : super(key: key);
#override
_FetchDataState createState() => _FetchDataState();
}
class _FetchDataState extends State<FetchDataPage> {
String _productUrl;
Widget pageWidget;
#override
Widget build(BuildContext context) {
pageWidget = _loadingWidget();
_productUrl = widget.text;
checkPrice(_productUrl);
return Scaffold(
body: Container(padding: EdgeInsets.all(20.0), child: pageWidget),
);
}
Widget _loadingWidget() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: CircularProgressIndicator(
backgroundColor: Colors.transparent,
valueColor: AlwaysStoppedAnimation<Color>(Colors.blueGrey),
),
),
SizedBox(height: 20.0),
Text(
"Checking Price...",
style: TextStyle(
color: Colors.blueGrey,
fontSize: 20.0,
fontWeight: FontWeight.w500,
),
),
],
);
}
Widget errorWidget() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: Icon(
Icons.sentiment_dissatisfied,
color: Colors.red,
size: 60.0,
),
),
SizedBox(height: 20.0),
Center(
child: Text(
"Product not found in database.\nPlease try again later.",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.blueGrey,
fontSize: 17.0,
fontWeight: FontWeight.w500,
),
),
),
],
);
}
void checkPrice(String productUrl) {
bool isUrl = isURL(productUrl, requireProtocol: true, requireTld: true);
if (!isUrl) {
RegExp regExp = new RegExp(r"((\w+:\/\/\S+)|(\w+[\.:]\w+\S+))[^\s,\.]");
setState(() {
productUrl = regExp.stringMatch(productUrl).toString();
});
}
/*
//setState is Working fine here!
setState(() {
pageWidget = errorWidget();
});
*/
var response = getLatestPrice(productUrl);
response.then((response) {
/*
//It's Not Working Here :(
setState(() {
pageWidget = errorWidget();
});
*/
print("Got Response: " + response.body.toString());
if (response.statusCode == 200) {
var loginData = json.decode(response.body);
bool status = loginData["status"];
print("STATUS: " + status.toString());
if (status) {
//This print statement is also working fine!
print(loginData["productUrl"]);
} else {
//This isn't working either
setState(() {
pageWidget = errorWidget();
});
}
} else {
//Not Working
setState(() {
pageWidget = errorWidget();
});
}
});
}
}
Future<http.Response> getLatestPrice(productUrl) async {
var url = Strings.baseUrl + 'api/checkPrice';
var response = await http.post(url, body: {
'product_url': productUrl,
}, headers: {
HttpHeaders.authorizationHeader:
"Basic " + base64Encode(utf8.encode('username:password'))
});
return response;
}
I fixed it by setting a bool instead:
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:validators/validators.dart';
import '../strings.dart';
class FetchDataPage extends StatefulWidget {
final String text;
FetchDataPage({Key key, #required this.text}) : super(key: key);
#override
_FetchDataState createState() => _FetchDataState();
}
class _FetchDataState extends State<FetchDataPage> {
String _productUrl;
bool showError = false;
#override
Widget build(BuildContext context) {
_productUrl = widget.text;
if (_productUrl != null) {
checkPrice(_productUrl);
}
return Scaffold(
body: Container(padding: EdgeInsets.all(20.0), child: pageWidget()),
);
}
Widget pageWidget() {
if (showError == false) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: CircularProgressIndicator(
backgroundColor: Colors.transparent,
valueColor: AlwaysStoppedAnimation<Color>(Colors.blueGrey),
),
),
SizedBox(height: 20.0),
Text(
"Checking Price...",
style: TextStyle(
color: Colors.blueGrey,
fontSize: 20.0,
fontWeight: FontWeight.w500,
),
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: Icon(
Icons.sentiment_dissatisfied,
color: Colors.red,
size: 60.0,
),
),
SizedBox(height: 20.0),
Center(
child: Text(
"Product not found in database.\nPlease try again later.",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.blueGrey,
fontSize: 17.0,
fontWeight: FontWeight.w500,
),
),
),
],
);
}
}
void checkPrice(String productUrl) {
bool isUrl = isURL(productUrl, requireProtocol: true, requireTld: true);
if (!isUrl) {
RegExp regExp = new RegExp(r"((\w+:\/\/\S+)|(\w+[\.:]\w+\S+))[^\s,\.]");
setState(() {
productUrl = regExp.stringMatch(productUrl).toString();
});
}
var response = getLatestPrice(productUrl);
response.then((response) {
if (response.statusCode == 200) {
var loginData = json.decode(response.body);
bool status = loginData["status"];
if (status) {
print(loginData["productUrl"]);
} else {
setState(() {
showError = true;
});
}
} else {
setState(() {
showError = true;
});
}
});
}
}
Future<http.Response> getLatestPrice(productUrl) async {
var url = Strings.baseUrl + 'api/checkPrice';
var response = await http.post(url, body: {
'product_url': productUrl,
}, headers: {
HttpHeaders.authorizationHeader:
"Basic " + base64Encode(utf8.encode('username:password'))
});
return response;
}