Can't show the list from my API in flutter - flutter

iam new to flutter and i tried to make an app using my own API, i tried running the app but the listview just showing anything besides no error occured, someone said i should use FutureListView but idk how to implemented in my code.
here is my homepage code
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart';
import 'package:medreminder/TipsAndTricks/models/tips.dart';
import 'package:medreminder/TipsAndTricks/models/tips_model.dart';
import 'package:medreminder/TipsAndTricks/screens/tips_details.dart';
import 'package:medreminder/TipsAndTricks/tips_repo.dart';
class TipsList extends StatefulWidget {
const TipsList({super.key});
#override
State<TipsList> createState() => _TipsListState();
}
class _TipsListState extends State<TipsList> {
List<Tips> listTips = [];
Repo repo = Repo();
getData() async {
listTips = await repo.getData();
}
#override
void initState() {
getData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Get.isDarkMode?Colors.grey[600]:Colors.white,
leading: IconButton(
onPressed: ()=>Get.back(),
icon: Icon(Icons.arrow_back_ios,
color: Get.isDarkMode?Colors.white:Colors.black
),
),
title: Text("Healthy Tips & Tricks", style: TextStyle(
color: Get.isDarkMode?Colors.white:Colors.black
),),
),
body: ListView.builder(
itemCount: listTips.length,
itemBuilder: (context, index){
Tips tips = listTips[index];
return Card(
child: ListTile(
title: Text(listTips[index].title),
subtitle: Text(listTips[index].source),
leading: Image.network(listTips[index].imageUrl),
trailing: Icon(Icons.arrow_forward_ios),
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context) => TipsDetails(listTips[index])));
},
),
);
})
);
}
}
my model class
class Tips {
final String title;
final String desc;
final String imageUrl;
final String source;
const Tips({
required this.title,
required this.desc,
required this.imageUrl,
required this.source,
});
factory Tips.fromJson(Map<String, dynamic> json) {
return Tips(
source: json['source'],
desc: json['desc'],
title: json['title'],
imageUrl: json['imageUrl']
);
}
}
my repository code
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:medreminder/TipsAndTricks/models/tips_model.dart';
class Repo{
final _baseUrl = 'http://10.0.2.2:8000/tips';
Future getData() async{
try {
final response = await http.get(Uri.parse(_baseUrl));
if(response.statusCode == 200){
print(response.body);
Map<String, dynamic> apiRespose = jsonDecode(response.body);
Iterable<dynamic> it = apiRespose['tips'];
//Iterable it = jsonDecode(response.body);
List<Tips> tips = it.map((e) => Tips.fromJson(e)).toList();
return tips;
}
} catch (e) {
print(e.toString());
}
}
}
if you guys needs to see more of my code, please let me know. any help would mean so much to me. thankyou guys

Related

E/LB (26008): fail to open file: No such file or directory -Flutter

I try to get a List from this Api(https://www.getpostman.com/collections/fa1296508e65891de558)
But there does no appear any Object. Console showing => "E/LB (26008): fail to open file: No such file or directory
".
I tried to print respone.statusCode but the result does'n apper in console.
I hope to solve this problem, Thank you.
What can be the problem here?
My code:
class ApiSetting{
static const String _baseUri='http://demo-api.mr-dev.tech/api/';
static const String users= '${_baseUri}users';
}
**User Model
** class User {
late int id;
late String firstName;
late String lastName;
late String email;
late String mobile;
late String bio;
late String jobTitle;
late String latitude;
late String longitude;
late String country;
late String image;
late String active;
late String emailVerifiedAt;
late String imagesCount;
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
firstName = json['first_name'];
lastName = json['last_name'];
email = json['email'];
mobile = json['mobile'];
bio = json['bio'];
jobTitle = json['job_title'];
latitude = json['latitude'];
longitude = json['longitude'];
country = json['country'];
image = json['image'];
active = json['active'];
emailVerifiedAt = json['email_verified_at'];
imagesCount = json['images_count'];
}
}
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:api_secand_project/api/api_setting.dart';
import 'package:api_secand_project/models/user.dart';
class UserApiController {
Future<List<User>> getUser() async {
var uri = Uri.parse(ApiSetting.users);
var response = await http.get(uri);
if (response.statusCode == 200) {
print(response.statusCode);
var jsonResponse = jsonDecode(response.body);
var userJsonArray = jsonResponse['data'] as List;
return userJsonArray
.map((jsonObject) => User.fromJson(jsonObject))
.toList();
}
return [];
}
}
import 'package:api_secand_project/api/controllers/user_api_controller.dart';
import 'package:api_secand_project/models/user.dart';
import 'package:flutter/material.dart';
class UsersScreen extends StatefulWidget {
const UsersScreen({Key? key}) : super(key: key);
#override
State<UsersScreen> createState() => _UsersScreenState();
}
class _UsersScreenState extends State<UsersScreen> {
List<User> _users=<User>[];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Users'),
),
body: FutureBuilder<List<User>>(
future: UserApiController().getUser(),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.waiting){
return const Center(
child: CircularProgressIndicator(),
);
}
else if(snapshot.hasData){
_users=snapshot.data!;
return ListView.builder(
itemCount: _users.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
radius: 30,
// child: NetworkImage(snapshot.data!.),
),
title: Text(_users[index].firstName),
subtitle: Text(_users[index].mobile),
);
},
);
}
else{
return Center(child: Text('No Data',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 28),),);
}
},
));
}
}
The question was not very clear, and there is no clear screenshot or message from the error console,
It seems that you are using the BLOC pattern and since part of the code is missing, you decide to create one from scratch, maybe it will help you, I thought not to publish it, but maybe something from here will help you
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class GetApi extends StatefulWidget {
const GetApi({super.key});
#override
State<GetApi> createState() => _GetApiState();
}
class _GetApiState extends State<GetApi> {
List<User> users = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Get Api")),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
getApi();
},
child: const Text("Get Api"),
),
Flexible(
child: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
User user = users[index];
return ListTile(
title: Text(user.name),
subtitle: Text(user.id),
);
}),
),
],
),
);
}
Future<void> getApi() async {
users = [];
Uri uri = Uri.parse("https://www.getpostman.com/collections/fa1296508e65891de558 ");
http.Response response = await http.get(uri);
if (response.statusCode == 200) {
//debugPrint("body: ${response.body}");
Map data = jsonDecode(response.body);
for (MapEntry item in data.entries) {
//debugPrint("key: ${item.key} value: ${item.value}");
if ("item" == item.key) {
List usersResponse = data["item"];
//debugPrint("users: ${users}");
for (dynamic json in usersResponse) {
User user = User.fromJson(json);
users.add(user);
//debugPrint("user: ${_user.name}");
}
}
}
if (!mounted) return;
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("succes -> status: ${response.statusCode}"),
backgroundColor: Colors.green,
),
);
} else {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("fail -> status: ${response.statusCode}"),
backgroundColor: Colors.red,
),
);
}
}
}
class User {
late String name;
late String id;
User.fromJson(Map<String, dynamic> json) {
name = json['name'];
id = json['id'];
}
}

Getting a getter length is called on Null error when trying to access List on Firebase using flutter

I am trying to retrieve and display a list of items on firebase, I have been able to access everything else on firebase apart from the list itself. I think the issue might be how I am going about retrieving the list because of the method in which it was saved. Here is the order model code
import 'package:butcherbox/models/productsModel.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:meta/meta.dart';
class Order {
Order(
{#required this.items,
//this.theItems,
this.location,
this.orderId,
this.time,
#required this.price});
final List<ProductsModel> items;
final String location;
final int orderId;
final Timestamp time;
final int price;
factory Order.fromMap(Map<String, dynamic> data) {
if (data == null) {
return null;
}
final List<ProductsModel> items = data['items'];
final String location = data['location'];
final int price = data['price'];
final int orderId = data['orderId'];
final Timestamp time = data['time'];
return Order(
items: items,
location: location,
price: price,
orderId: orderId,
time: time,
);
}
Map<String, dynamic> toMap() {
return {
'item': items.map((e) => e.toJson()).toList(),
'location': location,
'orderId': orderId,
'time': time,
'price': price
};
}
}
This is the code to display the data
import 'package:butcherbox/butch_widgets/order_list_tile.dart';
import 'package:butcherbox/models/ordersmodel.dart';
import 'package:butcherbox/services/database.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Orders extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.green[200],
title: Text(
'Orders',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.green[900]),
),
),
body: _buildContents(context),
);
}
Widget _buildContents(BuildContext context) {
final database = Provider.of<Database>(context, listen: false);
return StreamBuilder<List<Order>>(
stream: database.ordersStream(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final orders = snapshot.data;
// final children =
// orders.map((order) => Text(order.location)).toList();
final children =
orders.map((order) => OrderListTile(order: order)).toList();
return ListView(children: children);
}
if (snapshot.hasError) {
return Center(child: Text('Some Error Occurred'));
}
return Center(child: CircularProgressIndicator());
});
}
}
This is the widget for the UI
import 'package:butcherbox/models/ordersmodel.dart';
import 'package:flutter/material.dart';
class OrderListTile extends StatelessWidget {
final Order order;
const OrderListTile({Key key, #required this.order}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(
'Order No: ${order.orderId}',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.green[900]),
),
trailing: Text(
'Vendor: ${order.location}',
style: TextStyle(fontSize: 16),
),
subtitle: ListView.builder(
itemCount: order.items.length, <-- This is where the error is
shrinkWrap: true,
itemBuilder: (context, i) {
return Expanded(
child: Column(
children: [
Text('${order.items[i].name}'),
Text('${order.items[i].quantity.toString()}')
],
),
);
}),
isThreeLine: true,
);
}
}
This is the database code
import 'package:butcherbox/models/ordersmodel.dart';
import 'package:butcherbox/services/api_path.dart';
import 'package:meta/meta.dart';
import 'package:butcherbox/services/firestore_service.dart';
abstract class Database {
Future<void> createOrder(Order order);
Stream<List<Order>> ordersStream();
}
String docFromId() => DateTime.now().toIso8601String();
class FireStoreDatabase implements Database {
FireStoreDatabase({#required this.uid}) : assert(uid != null);
final String uid;
final _service = FireStoreService.instance;
Future<void> createOrder(Order order) => _service.setData(
//path: APIPath.order(uid, 'orderdetails'), data: order.toMap());
path: APIPath.order(uid, docFromId()),
data: order.toMap(),
);
Stream<List<Order>> ordersStream() => _service.collectionStream(
path: APIPath.orders(uid), builder: (data) => Order.fromMap(data));
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
class FireStoreService {
FireStoreService._();
static final instance = FireStoreService._();
Future<void> setData({String path, Map<String, dynamic> data}) async {
final reference = FirebaseFirestore.instance.doc(path);
print('$path: $data');
await reference.set(data);
}
Stream<List<T>> collectionStream<T>({
#required String path,
#required T Function(Map<String, dynamic> data) builder,
}) {
final reference = FirebaseFirestore.instance.collection(path);
final snapshots = reference.snapshots();
return snapshots.map((snapshot) => snapshot.docs
.map(
(snapshot) => builder(snapshot.data()),
)
.toList());
}
}
Yes actually you are right, so here are some keypoints,
Stream<List<Order>> ordersStream() => _service.collectionStream(
path: APIPath.orders(uid), builder: (data) =>
// This is supposed to be a list of Orders.
Order.fromMap(data));
You can try printing the data here so you see what I am talking about(it would be a List and not a singular object).

Flutter null check operator used on null value

This is my first month as coder. I am trying to develop nearby places app. When i used following codes im getting error of "null check operator used on a null value". But based on what i see or when i printed url and checked manually or when i used if condition i see no problem or no error. Just when i rendered screen im getting this error. I would like to ask if someone can point me what is wrong ? Thanks in advance!
The line im getting error is locationName: locationSuggestion!.query.pages[0]!.title. Probibly and following locationSuggestion class.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_udemy_examples/http_api_data/get_location_data_final.dart';
import 'package:flutter_udemy_examples/http_api_data/get_location_names.dart';
import 'package:flutter_udemy_examples/screens/login_ekrani.dart';
import 'package:flutter_udemy_examples/screens/map_screen.dart';
import 'login_ekrani.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../banner.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_udemy_examples/http_api_data/get_location_images.dart';
// ignore: must_be_immutable
class HomeScreen extends StatefulWidget {
#override
State<HomeScreen> createState() => HomeScreenState();
}
class HomeScreenState extends State<HomeScreen> {
LocationDataFinal? locationSuggestion;
bool isLoading = true;
#override
void initState() {
super.initState();
asyncInitState();
}
Future<void> asyncInitState() async {
await fecthlocationData();
}
Future fecthlocationData() async {
var locations = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
final double enlem = locations.latitude;
final double boylam = locations.longitude;
final url = Uri.parse(
"https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates%7Cpageimages%7Cdescription%7Cextracts&generator=geosearch&piprop=original&descprefersource=central&exlimit=20&exintro=1&explaintext=1&exsectionformat=plain&ggscoord=${enlem}%7C${boylam}&ggsradius=10000");
print(url);
final response = await http.get(url);
//print(response.body);
if (response.statusCode == 200) {
locationSuggestion = await locationDataFinalFromJson(response.body);
if (locationSuggestion != null) {
setState(() {
isLoading = false;
});
} else {
print("null1");
}
} else {
print("null2");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: _buildAppBar(context),
body: isLoading
? Center(
child: CircularProgressIndicator(),
)
: ListView(
children: [
MyBanner(
// info: locationSuggestion!.query.pages[0]!.description,
locationName: locationSuggestion!.query.pages[0]!.title,
imagePath:
locationSuggestion!.query.pages[0]!.original.source,
context: context,
),
MyBanner(
//info: locationSuggestion!.query.pages[1]!.description,
locationName: locationSuggestion!.query.pages[1]!.title,
imagePath:
locationSuggestion!.query.pages[1]!.original.source,
context: context,
),
MyBanner(
// info: locationSuggestion!.query.pages[2]!.description,
locationName: locationSuggestion!.query.pages[2]!.title,
imagePath:
locationSuggestion!.query.pages[2]!.original.source,
context: context,
),
MyBanner(
// info: locationSuggestion!.query.pages[3]!.description,
locationName: locationSuggestion!.query.pages[3]!.title,
imagePath:
locationSuggestion!.query.pages[3]!.original.source,
context: context,
),
MyBanner(
// info: locationSuggestion!.query.pages[4]!.description,
locationName: locationSuggestion!.query.pages[4]!.title,
imagePath:
locationSuggestion!.query.pages[4]!.original.source,
context: context,
),
],
),
);
}
AppBar _buildAppBar(BuildContext context) {
return AppBar(
automaticallyImplyLeading: false,
leading: RotatedBox(
quarterTurns: 2,
child: _buildExitButton(context),
),
actions: [
_buildOpenMapButton(),
_buildCallEmergencyNumberButton(),
],
titleSpacing: 25,
shadowColor: Colors.white,
elevation: 0.0,
backgroundColor: Colors.blue[800],
//titleSpacing: Padding(padding: EdgeInsets.fromLTRB(25.85.0, 0, 25.85.0, 0)),
title: Text("Traveler Doctor"),
);
}
Widget _buildCallEmergencyNumberButton() {
return IconButton(
disabledColor: Colors.red,
color: Colors.red,
icon: Icon(Icons.phone_enabled),
tooltip: "Local emergency number",
onPressed: null,
);
}
Widget _buildOpenMapButton() {
return IconButton(
disabledColor: Colors.orangeAccent,
color: Colors.limeAccent,
icon: Icon(Icons.map_rounded),
tooltip: "Map",
enableFeedback: false,
onPressed: () => {
Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) => MapScreen()))
},
);
}
}
Widget _buildExitButton(BuildContext context) {
return IconButton(
onPressed: () async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('KullaniciAdi', "");
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext context) => LoginEkrani()));
},
icon: Icon(
Icons.exit_to_app,
color: Colors.red,
),
tooltip: "Exit",
);
}
And this is the model im using for parsing api response
import 'dart:convert';
LocationDataFinal locationDataFinalFromJson(String str) =>
LocationDataFinal.fromJson(json.decode(str));
class LocationDataFinal {
LocationDataFinal({
required this.batchcomplete,
required this.query,
});
String batchcomplete;
Query query;
factory LocationDataFinal.fromJson(Map<String, dynamic> json) =>
LocationDataFinal(
batchcomplete: json["batchcomplete"],
query: Query.fromJson(json["query"]),
);
}
class Query {
Query({
required this.pages,
});
Map<String, Page> pages;
factory Query.fromJson(Map<String, dynamic> json) => Query(
pages: Map.from(json["pages"])
.map((k, v) => MapEntry<String, Page>(k, Page.fromJson(v))),
);
}
class Page {
Page({
required this.pageid,
required this.ns,
required this.title,
required this.index,
required this.coordinates,
required this.original,
required this.description,
required this.descriptionsource,
required this.extract,
});
int pageid;
int ns;
String title;
int index;
List<Coordinate> coordinates;
Original original;
String description;
String descriptionsource;
String extract;
factory Page.fromJson(Map<String, dynamic> json) => Page(
pageid: json["pageid"],
ns: json["ns"],
title: json["title"],
index: json["index"],
coordinates: List<Coordinate>.from(
json["coordinates"].map((x) => Coordinate.fromJson(x))),
original: json["original"] == null
? Original(
source:
"https://tigres.com.tr/wp-content/uploads/2016/11/orionthemes-placeholder-image-1.png",
width: 300,
height: 200)
: Original.fromJson(json["original"]),
description: json["description"] == null ? "asd" : json["description"],
descriptionsource:
json["descriptionsource"] == null ? " " : json["descriptionsource"],
extract: json["extract"],
);
}
class Coordinate {
Coordinate({
required this.lat,
required this.lon,
required this.primary,
required this.globe,
});
double lat;
double lon;
String primary;
Globe globe;
factory Coordinate.fromJson(Map<String, dynamic> json) => Coordinate(
lat: json["lat"].toDouble(),
lon: json["lon"].toDouble(),
primary: json["primary"],
globe: globeValues.map[json["globe"]]!,
);
}
enum Globe { EARTH }
final globeValues = EnumValues({"earth": Globe.EARTH});
class Original {
Original({
required this.source,
required this.width,
required this.height,
});
String source;
int width;
int height;
factory Original.fromJson(Map<String, dynamic> json) => Original(
source: json["source"],
width: json["width"],
height: json["height"],
);
}
class EnumValues<T> {
late Map<String, T> map;
late Map<T, String> reverseMap;
EnumValues(this.map);
}
I will be checking this post frequently.
Thanks in advance again.
Sincerely ur noob coder.
Would leave this as a comment but apparently I only have enough reputation to write answers.
In your Query object pages is a Map<String, Page> but you're accessing it with a int key: locationSuggestion!.query.pages[0]!.title
To access the map with an int key, it needs to be Map<int,Page> (or List<Page>)
Somewhat i solved issue by replacing
locationSuggestion!.query.pages[0]!.titlewith
locationSuggestion!.query.pages.values.elementAt(0).title
This way of adressing solved issue for me :)

I am able to save but not able to fetch the saved notes dynamically from DB, when I restart the app the notes are displaying. I am using sqflite

I'm a beginner in flutter, I'm building a simple Note app where users can enter, edit and save the note in local db. I'm able to save the notes to DB but it is not fetched as soon as it is saved. I need to restart the app to see the note list.
This is a Notes model class
import 'db_operations.dart';
class Note {
int id;
String title;
String body;
Note(this.id, this.title, this.body);
Note.fromMap(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
body = map['body'];
}
Map<String, dynamic> toMap(){
return {
DatabaseHelper.columnId : id,
DatabaseHelper.columnTitle : title,
DatabaseHelper.columnBody : body
};
}
#override
String toString(){
return 'Note{title : $title, body : $body}';
}
}
This is a Database helper class
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'model_notes.dart';
class DatabaseHelper {
static final _databaseName = "myNote.db";
static final _databaseVersion = 1;
static final table = 'notes_table';
static final columnId = 'id';
static final columnTitle = 'title';
static final columnBody = 'body';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
// lazily instantiate the db the first time it is accessed
_database = await initDatabase();
return _database;
}
initDatabase() async {
String path = join(await getDatabasesPath(), _databaseName);
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnTitle TEXT NOT NULL,
$columnBody TEXT NOT NULL
)
''');
}
Future<int> insert(Note note) async {
Database db = await instance.database;
if (note.title.trim().isEmpty) note.title = 'Untitled Note';
return await db.insert(table, {'title': note.title, 'body': note.body});
}
Future<List<Note>> getNotesFromDB() async {
final db = await database;
List<Note> notesList = [];
List<Map> maps = await db.query(table);
if (maps.length > 0) {
maps.forEach((map) {
notesList.add(Note.fromMap(map));
});
}
return notesList;
}
}
This is where I am adding notes
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:note_taking_app/constants/buttons_and_icons_misc(classes).dart';
import 'package:note_taking_app/db/db_operations.dart';
import 'package:note_taking_app/db/model_notes.dart';
import 'package:sqflite/sqflite.dart';
import 'main_screen.dart';
final bodyController = TextEditingController();
final headerController = TextEditingController();
final dbHelper = DatabaseHelper.instance;
class AddingNotes extends StatefulWidget {
#override
_AddingNotesState createState() => _AddingNotesState();
}
class _AddingNotesState extends State<AddingNotes> {
#override
void initState() {
super.initState();
bodyController.clear();
headerController.clear();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backwardsCompatibility: true,
leading: LeadingIcon(
callBack: () {
Navigator.pop(context);
},
),
backgroundColor: Colors.white.withOpacity(0.4),
actions: <Widget>[
ActionsIconButton(
icon: Icon(undo, color: black),
callBack: () {
debugPrint('undo tapped');
},
),
ActionsIconButton(
icon: Icon(redo, color: black),
callBack: () {
debugPrint('redo tapped');
},
),
ActionsIconButton(
icon: Icon(save, color: black),
callBack: () async {
debugPrint(bodyController.text);
debugPrint(headerController.text);
String title = headerController.text;
String body = bodyController.text;
Note note = Note(20, title, body);
var value = await dbHelper.insert(note);
print("if 1 is return then insert success and 0 then not inserted : $value");
Navigator.pop(context);
},
)
],
),
body: Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
HeaderBody(
textEditingController: headerController,
),
SizedBox(
height: 32.0,
),
Expanded(
child: NotesBody(
textEditingController: bodyController,
),
),
],
),
),
),
);
}
}
This is where I am displaying notes
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:note_taking_app/constants/text_and_decorations(methods).dart';
import 'package:note_taking_app/db/model_notes.dart';
import 'package:note_taking_app/ui/adding_notes.dart';
import 'package:note_taking_app/db/db_operations.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
List<Note> noteList = [];
#override
void initState() {
super.initState();
dbHelper.initDatabase();
setNotesFromDB();
}
setNotesFromDB() async{
print("Entered setNotes");
var fetchedNotes = await dbHelper.getNotesFromDB();
setState(() {
noteList = fetchedNotes;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: titleText,
backwardsCompatibility: false,
automaticallyImplyLeading: false,
backgroundColor: Colors.white.withOpacity(0.4),
),
floatingActionButton: Container(
height: 80.0,
width: 80.0,
child: FittedBox(
child: FloatingActionButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AddingNotes()));
},
child: const Icon(
Icons.add,
),
backgroundColor: Colors.green,
),
),
),
body: ListView.builder(
itemCount: noteList.length,
itemBuilder: (context, index){
return ListTile(
title: Text('${noteList[index]}'),
);
},
),
);
}
}
When I restart the app I'm getting user-entered notes. How can I make this dynamic, as a user enters a note and save it, it should be displayed on Main Screen. but I don't know how to do that. Any help here guys, I'm stuck at this..
The problem is that you are using a future, once it is complete there will be no updates, unless the Widget calling the getNotesFromDB() gets rebuild, which is the case when you restart the app or the emulator.
Moreover, you are also only fetching the notes in initState() of your MainScreen.
Option 1:
Try turning your ListView.builder in the body into a streambuilder, which is refreshing your Screen whenever a new note is saved.
Option 2:
Alternatively, implement a pull-to-refresh logic, which calls getNotesFromDB() for you. Checkout this video from the FlutterTeam to implement the feature.

Data is not inserting in multiple Hive Boxes

In my Flutter App, I have created 4 Hive Box for storing different values but data is inserting in only one box and when I try to insert data noting happening or not giving any exception or error. I have developed code as it is for all 4 box but I am not getting why my data is not inserting in Hive. If you run this project you understand everything..
First Box Model Class Code:
import 'package:hive/hive.dart';
part 'PasswordModel.g.dart';
#HiveType(typeId: 0)
class PasswordModel {
#HiveField(0)
final String websiteName;
#HiveField(1)
final String websiteAddress;
#HiveField(2)
final String userName;
#HiveField(3)
final String password;
#HiveField(4)
final String notes;
PasswordModel(
{this.websiteName, this.websiteAddress, this.userName, this.password, this.notes});
}
Second Box Model Class:
import 'package:hive/hive.dart';
part 'CardModel.g.dart';
#HiveType(typeId: 1)
class CardModel{
#HiveField(0)
final String cardName;
#HiveField(1)
final String cardNumber;
#HiveField(2)
final String userName;
#HiveField(3)
final String expiration;
#HiveField(4)
final String cvv;
#HiveField(5)
final String pin;
#HiveField(6)
final String note;
CardModel({this.cardName, this.cardNumber, this.userName, this.expiration, this.cvv, this.pin, this.note});
}
main.dart:
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:secret_keeper/screens/SplashScreen.dart';
import 'package:path_provider/path_provider.dart';
import 'package:secret_keeper/Database/Hive/BankModel.dart';
import 'package:secret_keeper/Database/Hive/CardModel.dart';
import 'package:secret_keeper/Database/Hive/NotesModel.dart';
import 'package:secret_keeper/Database/Hive/PasswordModel.dart';
void main(){
runApp(SecretKeeper());
}
class SecretKeeper extends StatefulWidget {
#override
_SecretKeeperState createState() => _SecretKeeperState();
}
class _SecretKeeperState extends State<SecretKeeper> {
#override
void initState() {
// TODO: implement initState
super.initState();
Hive.registerAdapter(PasswordModelAdapter());
Hive.registerAdapter(CardModelAdapter());
Hive.registerAdapter(BankModelAdapter());
Hive.registerAdapter(NotesModelAdapter());
_openBox();
}
Future _openBox() async {
WidgetsFlutterBinding.ensureInitialized();
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
Box passwordBox = await Hive.openBox<PasswordModel>('passwordBox');
Box cardBox = await Hive.openBox<CardModel>('cardBox');
Box bankBox = await Hive.openBox<BankModel>('bankBox');
Box notesBox = await Hive.openBox<NotesModel>('notesBox');
return;
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Secret Keeper",
debugShowCheckedModeBanner: false,
theme: ThemeData(
accentColor: Colors.white60,
primaryColor: Colors.white,
primaryIconTheme: IconThemeData(color: Colors.black),
fontFamily: "GoogleFonts",
),
home: SplashScreen(),
);
}
}
Class from where I am getting input. I have skipped UI code for better understanding and showed only method which call when User click on Submit button.
Input Class 1 method:
void addDataToHive() {
PasswordModel passwordModel = PasswordModel(
websiteName: websiteNameController.text,
websiteAddress: websiteAddressController.text,
userName: userNameController.text,
password: passwordController.text,
notes: notesController.text
);
var passwordBox = Hive.box<PasswordModel>('passwordBox');
passwordBox.add(passwordModel);
Navigator.pop(context);
}
Input Class 2 method:
void addDataToHive() {
CardModel cardModel = CardModel(
cardName: cardNameController.text,
cardNumber: cardNumberController.text,
userName: userNameController.text,
expiration: expirationController.text,
cvv: cvvController.text,
pin: pinController.text,
note: notesController.text
);
var cardBox = Hive.box<CardModel>('cardBox');
cardBox.add(cardModel);
Navigator.pop(context);
}
This is a class where I show list of data.
First Class Code:
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:secret_keeper/Database/Hive/PasswordModel.dart';
import 'package:secret_keeper/screens/home_screen/passwords/ShowData.dart';
class PasswordsNavigation extends StatefulWidget {
#override
_PasswordsNavigationState createState() => _PasswordsNavigationState();
}
class _PasswordsNavigationState extends State<PasswordsNavigation> {
var passwordBox = Hive.box<PasswordModel>('passwordBox');
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: _buildListView(),
)
],
),
);
}
Widget _buildListView() {
return WatchBoxBuilder(
box: passwordBox,
builder: (context, box) {
Map<dynamic, dynamic> raw = box.toMap();
List list = raw.values.toList();
return ListView.builder(
shrinkWrap: true,
itemCount: list.length,
itemBuilder: (context, index) {
PasswordModel passwordModel = list[index];
return ListTile(
title: Text(passwordModel.websiteName),
subtitle: Text(passwordModel.websiteAddress),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
passwordBox.deleteAt(index);
},
)
],
),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => ShowData(
id: index,
)));
},
);
},
);
},
);
}
}
Second Class Code:
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:secret_keeper/Database/Hive/CardModel.dart';
import 'package:secret_keeper/screens/home_screen/cards/ShowData.dart';
class CardsNavigation extends StatefulWidget {
#override
_CardsNavigationState createState() => _CardsNavigationState();
}
class _CardsNavigationState extends State<CardsNavigation> {
var cardBox = Hive.box<CardModel>('cardBox');
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: _buildListView(),
)
],
),
);
}
Widget _buildListView() {
return WatchBoxBuilder(
box: cardBox,
builder: (context, box) {
Map<dynamic, dynamic> raw = box.toMap();
List list = raw.values.toList();
return ListView.builder(
shrinkWrap: true,
itemCount: list.length,
itemBuilder: (context, index) {
CardModel cardModel = list[index];
return ListTile(
title: Text(cardModel.cardName),
subtitle: Text(cardModel.cardNumber),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
cardBox.deleteAt(index);
},
)
],
),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => ShowData(
id: index,
),
),
);
},
);
},
);
},
);
}
}
Same I have extra 2 box, but I add reference of 2 Box only, So my problem is data adding in only first box and remaining box not getting any data, but I don't know why?
For Full code Follow this Link: https://github.com/jaydip-pawar/Password-Manager-Flutter.git