Read data from Firestore reference - flutter

i have data stucture like:
/Admin/Dashboard/MRmZh9mixve1CV3M0EI8wfyDnb82/20220607/Anonymous/Entry
i want to read all that data that is under
/Admin/Dashboard/MRmZh9mixve1CV3M0EI8wfyDnb82
i tried this buts it returns empty
String collection = "/Admin/Dashboard/MRmZh9mixve1CV3M0EI8wfyDnb82";
await FirebaseFirestore.instance.collection(collection).get().then(
(res) => print("Successfully completed ${res}"),
onError: (e) => print("Error completing: $e"),
);
so basically i want lo read all the collections in it that has further documents in each collection

I could use this way to extract data from specific documents and collections.
final _firestore = FirebaseFirestore.instance;
void getMessages() async{
final docRef = await _firestore.collection('1234#123.com').doc('123123').collection('record').get();
for (var Ref in docRef.docs) {
print(Ref.data());
}
}
void getMessages44() async{
final docRef = await _firestore.collection('Admin').doc('Dashboard').collection('MRmZh9mixve1CV3M0EI8wfyDnb82').get();
for (var Ref in docRef.docs) {
print(Ref.data());
}
}
void test() async {
print("test");
// List<dynamic> userList = [];
QuerySnapshot querySnapshot = await _firestore.collection('1234#123.com').doc('123123').collection('record').where('Item', isEqualTo:"sdfsf").get();
// userList = querySnapshot.docs.map((e) => dynamic.User.fromMap(e.data())).toList();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
// final allData = querySnapshot.docs.map((doc) => doc.get('fieldName')).toList();
print(allData);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Record'),
leading: null,
actions: <Widget>[
IconButton(
icon: const Icon(Icons.add),
onPressed: (){
Navigator.pushNamed(context, creationCategory.id);
},
),
IconButton(
icon: const Icon(Icons.settings),
onPressed: () async {
// await getData();
// getMessages();
// getMessages();
getMessages44();
test();
// getMessages33();
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => const ItemDetailsScrrent()),
// );
},
),
],
),
body: SafeArea(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Trahs Collection',
style: const TextStyle(
color: Colors.black38, fontWeight: FontWeight.bold, fontSize: 40),
),
ItemStream(),
],
),
),
),
);
}

Related

Refresh flutter DataTable when alertdialog pressed

Problem :
Im trying to delete data from Flutter DataTable, when i pressed the alertdialog and click yes the Data already deleted on the Database but the data still shown in the screen until i click the back navigation button and back to list of user.
Expected :
The Datatable should automatically refreshed with current data minus the data that i deleted earlier.
Datatable
// ignore_for_file: deprecated_member_use
import 'package:flutter/material.dart';
import 'package:flutter_auth/Models/nasabah.dart';
import 'package:flutter_auth/network/nasabah_service.dart';
import 'package:flutter_auth/screens/Menu/DataNasabah/detailnasabah.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
class DataNasabah extends StatefulWidget {
#override
_DataNasabahState createState() => _DataNasabahState();
}
class _DataNasabahState extends State<DataNasabah> {
String nama_debitur = '';
List<Nasabah> _nasabah = [];
#override
void initState() {
super.initState();
_loadUserData();
_getNasabah();
}
_loadUserData() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var user = jsonDecode(localStorage.getString('user'));
if (user != null) {
setState(() {
nama_debitur = user['nama_debitur'];
});
}
}
_getNasabah() {
NasabahService.getUser().then((nasabah) {
if (mounted) {
setState(() {
_nasabah = nasabah;
});
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Data Nasabah'),
// backgroundColor: Color(0xff151515),
// automaticallyImplyLeading: false,
),
body: SingleChildScrollView(
child: PaginatedDataTable(
rowsPerPage: 10,
header: Align(
alignment: Alignment.center,
child: Text(
'Data Nasabah',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
// Text("Data Nasabah"),
columns: [
DataColumn(
label: Expanded(
child: Text(
'ID Nasabah',
textAlign: TextAlign.center,
)),
),
DataColumn(
label: Expanded(
child: Text(
'Nama Nasabah',
textAlign: TextAlign.center,
)),
),
DataColumn(
label: Expanded(
child: Text(
'Aksi',
textAlign: TextAlign.center,
)),
),
],
source: NasabahDataTableSource(userData: _nasabah, context: context),
),
),
);
}
}
class NasabahDataTableSource extends DataTableSource {
BuildContext context;
NasabahDataTableSource({this.context, this.userData});
final List<Nasabah> userData;
#override
DataRow getRow(int index) {
return DataRow.byIndex(
index: index,
cells: [
DataCell(Align(
alignment: Alignment.center,
child: Text(
"${userData[index].id}",
))),
DataCell(Align(
alignment: Alignment.center,
child: Text("${userData[index].nama_debitur}"),
)),
DataCell(
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: Icon(Icons.navigate_next),
color: Colors.blueAccent,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailNasabah(
nasabah: userData[index],
),
),
);
},
),
IconButton(
icon: Icon(Icons.delete),
color: Colors.red,
onPressed: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Hapus Data Nasabah'),
content: Text(
'Apakah anda yakin ingin menghapus data nasabah ini?'),
actions: [
FlatButton(child: Text('Yes'), onPressed: () {
NasabahService.deleteUser(userData[index].id);
Navigator.pop(context);
})
],
),
);
},
)
],
),
),
// DataCell(
// FlatButton(
// child: Icon(
// Icons.chevron_right,
// color: Colors.red,
// ),
// onPressed: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => DetailNasabah(
// nasabah: userData[index],
// ),
// ),
// );
// },
// ),
// ),
],
);
}
#override
bool get isRowCountApproximate => false;
#override
int get rowCount => userData.length;
#override
int get selectedRowCount => 0;
void sort<T>(Comparable<T> getField(Nasabah d), bool ascending) {
userData.sort((Nasabah a, Nasabah b) {
if (!ascending) {
final Nasabah c = a;
a = b;
b = c;
}
final Comparable<T> aValue = getField(a);
final Comparable<T> bValue = getField(b);
return Comparable.compare(aValue, bValue);
});
notifyListeners();
}
}
Api
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class Network {
final String _url = 'http://192.168.100.207:8080/api/';
// 192.168.1.2 is my IP, change with your IP address
var token;
_getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
token = jsonDecode(localStorage.getString('token'));
}
auth(data, apiURL) async {
var fullUrl = _url + apiURL;
return await http.post(fullUrl,
body: jsonEncode(data), headers: _setHeaders());
}
getData(apiURL) async {
var fullUrl = _url + apiURL;
await _getToken();
return await http.get(
fullUrl,
headers: _setHeaders(),
);
}
deleteData(apiURL, id) async {
var fullUrl = _url + apiURL + '/' + id.toString();
await _getToken();
return await http.delete(
fullUrl,
headers: _setHeaders(),
);
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
};
}
Service
import 'package:flutter_auth/Models/nasabah.dart';
import 'api.dart';
import 'dart:convert';
class NasabahService {
static String baseUrl = "mstdebitur";
static Future<List<Nasabah>> getUser() async {
final response = await Network().getData(baseUrl);
List<Nasabah> list = parseResponse(response.body);
return list;
}
static Future<List<Nasabah>> deleteUser(id) async {
final response = await Network().deleteData(baseUrl, id);
List<Nasabah> list = parseResponse(response.body);
return list;
}
static List<Nasabah> parseResponse(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Nasabah>((json) => Nasabah.fromJson(json)).toList();
}
}

What is the correct Provider<AuthBlock> for my DrawerNavigation Widget?

I am working on a simple mobile app with Google sign in capabilities.
So far, the app has been working, but with the latest step (the actual signing in) I am receiving the following error
════════ Exception caught by widgets library ═══════════════════════════════════
Error: Could not find the correct Provider<AuthBlock> above this DrawerNavigation Widget
I have tried the usual suspects; ensuring that the right packages are being imported, that it is due to me running on a virtual mobile device, and that a hot reboot might have been needed.
The issue persists however.
I had expected it to prompt the user to sign in with Google, but that is obviously not happening.
My code is as follows, and I believe the error is originating from line 54 which reads final authBlock = Provider.of(context);.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:to_do_list/blocks/auth_block.dart';
import 'package:to_do_list/screens/home_screen.dart';
import 'package:to_do_list/screens/categories_screen.dart';
import 'package:to_do_list/screens/todos_by_category.dart';
import 'package:to_do_list/service/category_service.dart';
import 'package:flutter_signin_button/flutter_signin_button.dart';
class DrawerNavigation extends StatefulWidget {
#override
_DrawerNavigationState createState() => _DrawerNavigationState();
}
class _DrawerNavigationState extends State<DrawerNavigation> {
//List<Widget> _categoryList = List<Widget>(); //Has been depricated
List<Widget> _categoryList = List<Widget>.generate(0, (index) {
//Widget obj = Widget();
//obj.id = index;
return;
});
CategoryService _categoryService = CategoryService();
#override
initState() {
super.initState();
getAllCategories();
}
getAllCategories() async {
var categories = await _categoryService.readCategories();
categories.forEach((category) {
setState(() {
_categoryList.add(InkWell(
onTap: () => Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new TodosByCategory(
category: category['name'],
))),
child: ListTile(
title: Text(category['name']),
),
));
});
});
}
#override
Widget build(BuildContext context) {
final authBlock = Provider.of<AuthBlock>(context);
return Container(
child: Drawer(
child: ListView(
children: <Widget>[
// UserAccountsDrawerHeader(
// currentAccountPicture: CircleAvatar(
// backgroundImage: NetworkImage(
// 'https://cdn.shopify.com/s/files/1/1733/6579/products/product-image-602960373_1024x1024#2x.jpg')),
// accountName: Text('Meena Bobeena'),
// accountEmail: Text('meena#happycat.com'),
// decoration: BoxDecoration(color: Colors.blue),
// ),
Column(
children: [
SignInButton(
Buttons.Google,
onPressed: () => authBlock.loginWithGoogle(),
),
],
),
ListTile(
leading: Icon(Icons.home),
title: Text('Home'),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => (HomeScreen()))),
),
ListTile(
leading: Icon(Icons.view_list),
title: Text('Categories'),
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => (CategoriesScreen()))),
),
Divider(),
Column(
children: _categoryList,
)
],
),
),
);
}
}
As requested, the following is how the DrawerNavigation is called.
import 'package:flutter/material.dart';
import 'package:to_do_list/helpers/drawer_navigation.dart';
import 'package:to_do_list/screens/todo_screen.dart';
import 'package:to_do_list/service/todo_service.dart';
import 'package:to_do_list/models/todo.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
TodoService _todoService;
//List<Todo> _todoList = List<Todo>(); // Has been deprecated
List<Todo> _todoList = List<Todo>.generate(0, (index) {
Todo obj = Todo();
obj.id = index;
return obj;
});
#override
initState() {
super.initState();
getAllTodos();
}
getAllTodos() async {
_todoService = TodoService();
//_todoList = List<Todo>(); //Has been depricated
_todoList = List<Todo>.generate(0, (index) {
Todo obj = Todo();
obj.id = index;
return obj;
});
var todos = await _todoService.readTodos();
todos.forEach((todo) {
setState(() {
var model = Todo();
model.id = todo['id'];
model.title = todo['title'];
model.description = todo['description'];
model.category = todo['category'];
model.todoDate = todo['todoDate'];
model.isFinished = todo['isFinished'];
_todoList.add(model);
});
});
}
_deleteFormDialog(BuildContext context, categoryId) {
return showDialog(
context: context,
barrierDismissible: true,
builder: (param) {
return AlertDialog(
actions: <Widget>[
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red),
foregroundColor: MaterialStateProperty.all(Colors.white)),
onPressed: () async {
Navigator.pop(context);
},
child: Text('Cancel'),
),
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green),
foregroundColor: MaterialStateProperty.all(Colors.white)),
// This doesn't delete :'(
onPressed: () async {
var result = await _todoService.deleteTodos(categoryId);
//print(result);
if (result > 0) {
print(result);
Navigator.pop(context);
getAllTodos();
_showSuccessSnackBar(Text('Deleted'));
}
},
child: Text('Delete'),
),
],
title: Text('Are you sure you wish to delete this To Do item ?'),
);
});
}
_showSuccessSnackBar(message) {
var _snackBar = SnackBar(content: message);
ScaffoldMessenger.of(context).showSnackBar(_snackBar);
//_globalKey.currentState.showSnackBar(_snackBar); === Depreciated
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Meenas To Do List')),
drawer: DrawerNavigation(),
body: ListView.builder(
itemCount: _todoList.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(top: 8, left: 8, right: 8),
child: Card(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: ListTile(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(_todoList[index].title ?? 'No Title'),
IconButton(
icon: Icon(Icons.delete, color: Colors.red),
onPressed: () {
_deleteFormDialog(context, _todoList[index].id);
},
)
],
),
subtitle: Text(_todoList[index].category ?? 'No Category'),
trailing: Text(_todoList[index].todoDate ?? 'No Date'),
),
),
);
}),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => TodoScreen())),
child: Icon(Icons.add)),
);
}
}
This is the code where I instantiate the provider
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:to_do_list/service/auth_service.dart';
class AuthBlock {
final authService = AuthService();
final googleSignIn = GoogleSignIn(scopes: ['email']);
Stream<User> get currentUser => authService.currentUser;
loginWithGoogle() async {
try {
final GoogleSignInAccount googleUser = await googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
);
//Firebase Sign In
final result = await authService.signInWithCredential(credential);
print('${result.user.displayName}');
} catch (error) {
print(error);
}
}
logout() {
authService.logout();
}
}
The main.dart
import 'package:flutter/material.dart';
import 'package:to_do_list/src/app.dart';
void main() => runApp(App());
Did you wrap your app with the provider? E.g. like you see here
runApp(
/// Providers are above [MyApp] instead of inside it, so that tests
/// can use [MyApp] while mocking the providers
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
],
child: const MyApp(),
),
);

The named parameter 'fileExtension' is not defined

I am using some code from an older version of File Picker, the null safety version will mess up my other code so I'm using 1.1.1.
the code isn't incorrect because it the same on the file picker package example. can anyone help plz?
the code goes as followed
void openFileExplorer() async {
try {
_path = null;
if (_multiPick) {
_paths = await FilePicker.getMultiFilePath(
type: _pickType, **fileExtension**: _extension);
} else {
_path = await FilePicker.getFilePath(
type: _pickType, **fileExtension**: _extension);
}
uploadToFirebase();
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
}
Try this one
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: UploadMultipleImageDemo(),
);
}
}
class UploadMultipleImageDemo extends StatefulWidget {
UploadMultipleImageDemo() : super();
final String title = 'Firebase Storage';
#override
UploadMultipleImageDemoState createState() => UploadMultipleImageDemoState();
}
class UploadMultipleImageDemoState extends State<UploadMultipleImageDemo> {
//
String _path;
Map<String, String> _paths;
List<String> extensions;
FileType _pickType;
bool _multiPick = false;
GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
List<StorageUploadTask> _tasks = <StorageUploadTask>[];
void openFileExplorer() async {
try {
_path = null;
if (_multiPick) {
_paths = await FilePicker.getMultiFilePath(
type: _pickType, allowedExtensions: extensions);
} else {
_path = await FilePicker.getFilePath(
type: _pickType, allowedExtensions: extensions);
}
//uploadToFirebase();
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
}
// uploadToFirebase() {
// if (_multiPick) {
// _paths.forEach((fileName, filePath) => {upload(fileName, filePath)});
// } else {
// if (_path != null) {
// String fileName = _path
// .split('/')
// .last;
// String filePath = _path;
// upload(fileName, filePath);
// }
// }
// }
// upload(fileName, filePath) {
// extensions = fileName.toString().split('.').last as List<String>;
// StorageReference storageRef =
// FirebaseStorage.instance.ref().child(fileName);
// final StorageUploadTask uploadTask = storageRef.putFile(
// File(filePath),
// StorageMetadata(
// contentType: '$_pickType/$extensions',
// ),
// );
// setState(() {
// _tasks.add(uploadTask);
// });
// extensions = null;
// }
dropDown() {
return DropdownButton(
hint: new Text('Select'),
value: _pickType,
items: <DropdownMenuItem>[
new DropdownMenuItem(
child: new Text('Audio'),
value: FileType.audio,
),
new DropdownMenuItem(
child: new Text('Image'),
value: FileType.image,
),
new DropdownMenuItem(
child: new Text('Video'),
value: FileType.video,
),
new DropdownMenuItem(
child: new Text('Any'),
value: FileType.any,
),
],
onChanged: (value) => setState(() {
_pickType = value;
}),
);
}
String _bytesTransferred(StorageTaskSnapshot snapshot) {
return '${snapshot.bytesTransferred}/${snapshot.totalByteCount}';
}
#override
Widget build(BuildContext context) {
final List<Widget> children = <Widget>[];
_tasks.forEach((StorageUploadTask task) {
final Widget tile = UploadTaskListTile(
task: task,
onDismissed: () => setState(() => _tasks.remove(task)),
onDownload: () => downloadFile(task.lastSnapshot.ref),
);
children.add(tile);
});
return new MaterialApp(
home: new Scaffold(
key: _scaffoldKey,
appBar: new AppBar(
title: Text(widget.title),
),
body: new Container(
padding: EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
dropDown(),
SwitchListTile.adaptive(
title: Text('Pick multiple files', textAlign: TextAlign.left),
onChanged: (bool value) => setState(() => _multiPick = value),
value: _multiPick,
),
OutlineButton(
onPressed: () => openFileExplorer(),
child: new Text("Open file picker"),
),
SizedBox(
height: 20.0,
),
Flexible(
child: ListView(
children: children,
),
),
],
),
),
),
);
}
Future<void> downloadFile(StorageReference ref) async {
final String url = await ref.getDownloadURL();
final http.Response downloadData = await http.get(url);
final Directory systemTempDir = Directory.systemTemp;
final File tempFile = File('${systemTempDir.path}/tmp.jpg');
if (tempFile.existsSync()) {
await tempFile.delete();
}
await tempFile.create();
final StorageFileDownloadTask task = ref.writeToFile(tempFile);
final int byteCount = (await task.future).totalByteCount;
var bodyBytes = downloadData.bodyBytes;
final String name = await ref.getName();
final String path = await ref.getPath();
print(
'Success!\nDownloaded $name \nUrl: $url'
'\npath: $path \nBytes Count :: $byteCount',
);
_scaffoldKey.currentState.showSnackBar(
SnackBar(
backgroundColor: Colors.white,
content: Image.memory(
bodyBytes,
fit: BoxFit.fill,
),
),
);
}
}
class UploadTaskListTile extends StatelessWidget {
const UploadTaskListTile(
{Key key, this.task, this.onDismissed, this.onDownload})
: super(key: key);
final StorageUploadTask task;
final VoidCallback onDismissed;
final VoidCallback onDownload;
String get status {
String result;
if (task.isComplete) {
if (task.isSuccessful) {
result = 'Complete';
} else if (task.isCanceled) {
result = 'Canceled';
} else {
result = 'Failed ERROR: ${task.lastSnapshot.error}';
}
} else if (task.isInProgress) {
result = 'Uploading';
} else if (task.isPaused) {
result = 'Paused';
}
return result;
}
String _bytesTransferred(StorageTaskSnapshot snapshot) {
return '${snapshot.bytesTransferred}/${snapshot.totalByteCount}';
}
#override
Widget build(BuildContext context) {
return StreamBuilder<StorageTaskEvent>(
stream: task.events,
builder: (BuildContext context,
AsyncSnapshot<StorageTaskEvent> asyncSnapshot) {
Widget subtitle;
if (asyncSnapshot.hasData) {
final StorageTaskEvent event = asyncSnapshot.data;
final StorageTaskSnapshot snapshot = event.snapshot;
subtitle = Text('$status: ${_bytesTransferred(snapshot)} bytes sent');
} else {
subtitle = const Text('Starting...');
}
return Dismissible(
key: Key(task.hashCode.toString()),
onDismissed: (_) => onDismissed(),
child: ListTile(
title: Text('Upload Task #${task.hashCode}'),
subtitle: subtitle,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Offstage(
offstage: !task.isInProgress,
child: IconButton(
icon: const Icon(Icons.pause),
onPressed: () => task.pause(),
),
),
Offstage(
offstage: !task.isPaused,
child: IconButton(
icon: const Icon(Icons.file_upload),
onPressed: () => task.resume(),
),
),
Offstage(
offstage: task.isComplete,
child: IconButton(
icon: const Icon(Icons.cancel),
onPressed: () => task.cancel(),
),
),
Offstage(
offstage: !(task.isComplete && task.isSuccessful),
child: IconButton(
icon: const Icon(Icons.file_download),
onPressed: onDownload,
),
),
],
),
),
);
},
);
}
}

The getter 'name' was called on null

I'm trying to make an app that has basically the same mechanics as a simple todo-app. My problem is, when I try to open the screen where I can create a new project/todo(new_project_screen), there should be loaded some TextFields, but they don't. Instead, this error occurs. I tried several solutions from stackoverflow, but nothing worked and I have no idea why it's not working.(sorry for my bad english, I'm not a native xD)
Here is my code:
main.dart:
import 'package:flutter/material.dart';
import 'package:leisy/surface/main_screen.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(App());
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Leisy',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MainScreen(),
);
}
}
main_screen.dart:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:leisy/db/database_helper.dart';
import 'package:leisy/model/project.dart';
import 'package:leisy/surface/settings_screen.dart';
import 'package:leisy/surface/new_project_screen.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
DatabaseHelper databaseHelper = DatabaseHelper();
List<Project> projectList = [];
int count = 0;
#override
Widget build(BuildContext context) {
if (projectList == null) {
projectList = <Project>[];
updateListView();
}
debugPrint("Building entire main screen scaffold");
return Scaffold(
appBar: AppBar(
title: Text("Leisy"),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Center(
child: Text(
"Menü",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 25,
),
),
),
decoration: BoxDecoration(color: Colors.blue),
),
ListTile(
leading: Icon(Icons.home),
title: Text('Home'),
onTap: () => {Navigator.of(context).pop()},
),
ListTile(
leading: Icon(Icons.add),
title: Text('Neues Projekt'),
onTap: () => {
Navigator.of(context).push(new MaterialPageRoute(
builder: (context) => new NewProjectScreen()))
},
),
ListTile(
leading: Icon(Icons.settings),
title: Text('Einstellungen'),
onTap: () => {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SettingsScreen()))
},
)
],
),
),
body: getProjectListView(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: navigateToNewProject,
),
);
}
ListView getProjectListView() {
TextStyle titleStyle = Theme.of(context).textTheme.subtitle1;
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.blue,
),
title: Text(
this.projectList[position].name,
style: titleStyle,
),
subtitle: Text(this.projectList[position].date),
onTap: () {
debugPrint('ListTile Tapped');
//navigateToDetail() einfügen
},
),
);
});
}
void _showSnackBar(BuildContext context, String message) {
final snackBar = SnackBar(
content: Text(message),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
void navigateToNewProject() async {
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) => NewProjectScreen()));
if (result == true) {
updateListView();
}
}
void updateListView() {
final Future<Database> dbFuture = databaseHelper.initDB();
dbFuture.then((database) {
Future<List<Project>> projectListFuture = databaseHelper.getProjectList();
projectListFuture.then((projectList) {
setState(() {
this.projectList = projectList;
this.count = projectList.length;
});
});
});
}
}
new_project_screen.dart:
import 'package:flutter/material.dart';
import 'package:leisy/db/database_helper.dart';
import 'package:leisy/model/project.dart';
import 'package:leisy/surface/main_screen.dart';
import 'package:leisy/surface/settings_screen.dart';
class NewProjectScreen extends StatefulWidget {
#override
_NewProjectScreenState createState() => _NewProjectScreenState();
}
class _NewProjectScreenState extends State<NewProjectScreen> {
Project project;
DatabaseHelper helper = DatabaseHelper();
TextEditingController nameController = TextEditingController();
TextEditingController dateController = TextEditingController();
TextEditingController locationController = TextEditingController();
#override
Widget build(BuildContext context) {
nameController.text = project.name;
dateController.text = project.date;
locationController.text = project.location;
return Scaffold(
appBar: AppBar(
title: Text("Neues Projekt"),
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Center(
child: Text(
"Menü",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 25,
),
),
),
decoration: BoxDecoration(color: Colors.blue),
),
ListTile(
leading: Icon(Icons.home),
title: Text('Home'),
onTap: () => {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => MainScreen()))
},
),
ListTile(
leading: Icon(Icons.add),
title: Text('Neues Projekt'),
onTap: () => {Navigator.of(context).pop()},
),
ListTile(
leading: Icon(Icons.settings),
title: Text('Einstellungen'),
onTap: () => {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SettingsScreen()))
},
)
],
),
),
body: Padding(
padding: EdgeInsets.all(8.0),
child: ListView(
children: <Widget>[
TextField(
controller: nameController,
decoration: InputDecoration(labelText: 'Name'),
style: TextStyle(fontSize: 20),
onChanged: (value) {
setState(() {
updateName();
});
},
),
TextField(
decoration: InputDecoration(labelText: 'Datum'),
style: TextStyle(fontSize: 20),
onChanged: (value) {
setState(() {
updateDate();
});
},
),
TextField(
decoration: InputDecoration(labelText: 'Ort'),
style: TextStyle(fontSize: 20),
onChanged: (value) {
setState(() {
updateLocation();
});
},
),
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Theme.of(context).primaryColorDark),
),
child: Text('Speichern'),
onPressed: () {
setState(() {
_save();
});
},
)),
Expanded(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Theme.of(context).primaryColorDark),
),
child: Text('Abbrechen'),
onPressed: () {
setState(() {
_cancel();
});
},
)),
],
)
],
)
)
);
}
void _save() async {
Navigator.pop(context, true);
await helper.insertProject(project);
}
void _showSnackBar(String message) {
SnackBar snackBar = SnackBar(content: Text(message));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
void _cancel() async {
Navigator.pop(context, true);
_showSnackBar('Vorgang abgebrochen');
}
void updateName() {
project.name = nameController.text;
}
void updateDate() {
project.date = dateController.text;
}
void updateLocation() {
project.location = locationController.text;
}
}
project.dart:
class Project {
int _id;
String _name;
String _date;
String _location;
String _personaldb;
Project(this._name, this._date, this._location, this._personaldb);
Project.withId(
this._id, this._name, this._date, this._location, this._personaldb);
int get id => _id;
String get name => _name;
String get date => _date;
String get location => _location;
String get personalDB => _personaldb;
set name(String newName) {
if (newName.length <= 63) {
this._name = newName;
}
}
set date(String newDate) {
this._date = newDate;
}
set location(String newLocation) {
this._location = newLocation;
}
set personalDB(String newPersonalDB) {
this._personaldb = newPersonalDB;
}
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
if (id != null) {
map['id'] = _id;
}
map['name'] = _name;
map['date'] = _date;
map['location'] = _location;
map['personalDB'] = _personaldb;
return map;
}
Project.fromMapObject(Map<String, dynamic> map) {
this._id = map['id'];
this._name = map['name'];
this._date = map['date'];
this._location = map['location'];
this._personaldb = map['personalDB'];
}
}
database_helper.dart:
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:leisy/model/project.dart';
class DatabaseHelper {
static DatabaseHelper _databaseHelper;
static Database _database;
String projectTable = 'project_table';
String colId = 'id';
String colName = 'name';
String colDate = 'date';
String colLocation = 'location';
String colPersonalDB = 'personalDB';
DatabaseHelper._createInstance();
factory DatabaseHelper() {
if (_databaseHelper == null) {
_databaseHelper = DatabaseHelper._createInstance();
}
return _databaseHelper;
}
Future<Database> get database async {
if (_database == null) {
_database = await initDB();
}
return _database;
}
Future<Database> initDB() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'projects.db';
var projectsDB = await openDatabase(path, version: 1, onCreate: _createDB);
return projectsDB;
}
void _createDB(Database db, int newVersion) async {
await db.execute('CREATE TABLE $projectTable('
'$colId INTEGER PRIMARY KEY AUTOINCREMENT,'
'$colName TEXT,'
'$colDate TEXT,'
'$colLocation TEXT,'
'$colPersonalDB TEXT)');
}
Future<List<Map<String, dynamic>>> getProjectMapList() async {
Database db = await this.database;
var result = await db.query(projectTable);
return result;
}
Future<int> insertProject(Project project) async {
Database db = await this.database;
var result = await db.insert(projectTable, project.toMap());
return result;
}
Future<int> updateProject(Project project) async {
var db = await this.database;
var result = await db.update(projectTable, project.toMap(), where: '$colId = ?', whereArgs: [project.id]);
return result;
}
Future<int> deleteProject(int id) async {
var db = await this.database;
int result = await db.delete(projectTable, where: '$colId = $id');
return result;
}
Future<int> getCount() async {
Database db = await this.database;
List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT (*) from $projectTable');
int result = Sqflite.firstIntValue(x);
return result;
}
Future<List<Project>> getProjectList() async {
var projectMapList = await getProjectMapList();
int count = projectMapList.length;
List<Project> projectList = <Project>[];
for (int i = 0; i < count; i++) {
projectList.add(Project.fromMapObject(projectMapList[i]));
}
return projectList;
}
}
Error:
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building NewProjectScreen(dirty, state: _NewProjectScreenState#670bc):
The getter 'name' was called on null.
Receiver: null
Tried calling: name
The relevant error-causing widget was:
NewProjectScreen file:///C:/Users/gabri/AndroidStudioProjects/leisy/lib/surface/main_screen.dart:116:89
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _NewProjectScreenState.build (package:leisy/surface/new_project_screen.dart:24:35)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4667:11)
...
====================================================================================================
If anybody can help me, I would really appreciate it. And if anything in my code is inconvenient or badly implemented, please be kind with me I'm a beginner at this.
The file new_project_screen.dart has the problem
To be exact, the problem can be found in lines 24:35
And seems like that project variable is null project.name;
That is because you are creating Project project but isn't instancied yet. Is just a null variable
See the image below, will help you to understand a bit:
https://dartpad.dev/1ebc897cd3f547cc0b79e52290a63653
So to fix it, you need to create the instance previously

Flutter Navigator.pop() keeps the Dialog Box partially visible with black shadow background

sorry for the long explaination but I think I have to be very clear about the topic.
I have been running in this issue for last couple of weeks. I am using flutter_bloc package.
I have a simple Search page(ProposalSearchPage) with searchbox and listview. Listview gets build based on the search keyword which dispatches KeywordsearchEvent. on Clicking the setting icon it opens of ProposalSearchSetting page which is a dialog box page.
Based on this structure I have two events used in the bloc. One for the keyword search and another for the Advance filter search.
In advance searching page after applying filters. Inside a button there I dispatched FilterSearchEvent and have used Navigation.pop(context) to return to ProposalSearchPage.
Based on the state change The listview renders for both the searches, but for the Adavance filter search, the ProposalSearchSetting dialog box is partially visible. The filter button in there are clickable. It dismiss when I click backarrow button.
I don't know why Navigator.pop is adding page to stack instead of popping the stack.
#PROPOSALSEARCH PAGE
class ProposalSearchPage extends StatefulWidget {
final UserProfileBloc userProfileBloc;
final MenuBloc menuBloc;
final String authToken;
ProposalSearchPage({this.userProfileBloc, this.menuBloc, this.authToken})
: assert(menuBloc != null),
assert(userProfileBloc != null);
#override
_ProposalSearchPageState createState() => _ProposalSearchPageState();
}
class _ProposalSearchPageState extends State<ProposalSearchPage> {
UserProfileBloc get _userProfileBloc => widget.userProfileBloc;
List filteredProposal = [];
String get _authToken => widget.authToken;
MenuBloc get _menuBloc => widget.menuBloc;
ProposalSearchBloc _proposalSearchBloc;
String searchedKeyword = "";
int searchProposalPage = 1;
#override
void initState() {
_proposalSearchBloc =
ProposalSearchBloc(proposalRepository: ProposalListingRepo());
_menuBloc.dispatch(MenuResponseFetchedEvent());
super.initState();
}
#override
void dispose() {
_proposalSearchBloc.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff2b57ff),
leading: IconButton(
icon: Icon(Icons.chevron_left),
onPressed: () {
Navigator.of(context).pop();
},
),
actions: <Widget>[
IconButton(
icon: new Icon(CupertinoIcons.gear_big),
onPressed: () {
/* Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProposalSearchSetting(
proposalSearchBloc: _proposalSearchBloc,
menuBloc: _menuBloc,
userProfileBloc: _userProfileBloc,
context: context),
fullscreenDialog: true,
),
);*/
showDialog<FilterProposalPost>(
context: context,
builder: (context) {
return ProposalSearchSetting(
proposalSearchBloc: _proposalSearchBloc,
menuBloc: _menuBloc,
userProfileBloc: _userProfileBloc,
context: context);
});
}),
],
title: Center(
child: Container(
width: 250.0,
height: 35.0,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.all(Radius.circular(7.0))),
child: CupertinoTextField(
placeholder: 'search here.',
style: TextStyle(
color: Colors.white,
),
onSubmitted: (keyword) {
print(keyword);
searchedKeyword = keyword;
FilterProposalPost filterProposalPost =
_buildSearchQueryParameter(keyword);
// print(query);
_proposalSearchBloc.proposalFilterPostParam(filterProposalPost);
},
),
),
),
),
body: SearchListing(_proposalSearchBloc, _authToken),
);
}
FilterProposalPost _buildSearchQueryParameter(String keyword) {
return FilterProposalPost(
........
);
}
}
}
class SearchListing extends StatelessWidget {
final ProposalSearchBloc _proposalSearchBloc;
final String _authToken;
SearchListing(this._proposalSearchBloc, this._authToken);
#override
Widget build(BuildContext context) {
return BlocBuilder(
bloc: _proposalSearchBloc,
// ignore: missing_return
builder: (context, state) {
if (state is ProposalSearchFetchingState) {
return Center(
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation(Color(0xff2b57ff))),
);
} else if (state is ProposalSearchFetchedState) {
final filteredProposal = state.filteredProposal;
print(filteredProposal.length.toString);
return _buildSearchProposalList(filteredProposal);
}
},
);
}
Widget _buildSearchProposalList(List searchedProposals) {
return ListView.builder(
itemCount: searchedProposals.length + 1,
itemBuilder: (context, position) {
return position >= searchedProposals.length
? _buildLoaderListItem()
: ProposalCardFactory(
proposal: searchedProposals[position],
authToken: _authToken,
);
});
}
Widget _buildLoaderListItem() {
return Center(
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation(Color(0xff2b57ff))));
}
}
#ProposalSearchSettingPage
class ProposalSearchSetting extends StatefulWidget {
final UserProfileBloc userProfileBloc;
final ProposalSearchBloc proposalSearchBloc;
final MenuBloc menuBloc;
final BuildContext context;
final Function() notifyParent;
ProposalSearchSetting({this.notifyParent,
this.proposalSearchBloc,
this.userProfileBloc,
this.menuBloc,
this.context});
#override
_ProposalSearchSettingState createState() =>
_ProposalSearchSettingState();
}
class _ProposalSearchSettingState extends State<ProposalSearchSetting>
with SingleTickerProviderStateMixin {
UserProfileBloc get _userProfileBloc => widget.userProfileBloc;
ProposalSearchBloc get _proposalSearchBloc => widget.proposalSearchBloc;
List<String> selectedOptions = [];
String resultBy;
List<String> industries;
List<String> stages;
List<String> locations;
List<String> languages;
List<String> countries;
List<String> regionsValue = [];
MenuBloc get _menuBloc => widget.menuBloc;
Animation<double> animation;
AnimationController controller;
double startingPoint;
#override
void initState() {
super.initState();
}
#override
void dispose() {
_userProfileBloc.dispose();
_proposalSearchBloc.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
//double startingPoint = MediaQuery.of(context).size.height;
return MaterialApp(
theme: ThemeData(
buttonTheme: ButtonThemeData(
minWidth: 200.0,
height: 40.0,
buttonColor: Color(0xff2b57ff),
textTheme: ButtonTextTheme.primary)),
home: Scaffold(
body: BlocBuilder(
bloc: _menuBloc,
// ignore: missing_return
builder: (context, state) {
if (state is MenuResponseFetchedState) {
MenuListData _menuListData = state.menuListData;
return Padding(
padding: const EdgeInsets.only(top: 100.0),
child: Center(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () async {
resultBy = await showDialog(
context: context,
builder: (context) {
return ResultBySearchDialog(
userProfileBloc: _userProfileBloc,
menuListData: _menuListData,
title: 'Result By:',
options: _menuListData.displayBy.values
.toList());
});
},
color: Color(0xff2b57ff),
child: Text(
'RESULT BY',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () async {
countries = await showDialog(
context: context,
builder: (context) {
return CountrySearchDialog(
userProfileBloc: _userProfileBloc,
menuListData: _menuListData,
title: 'Select Countries',
selectedOptions: selectedOptions,
onSelectedOptionListChanged: (options) {
selectedOptions = options;
print(selectedOptions);
});
});
},
color: Color(0xff2b57ff),
child: Text(
'COUNTRY',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () async {
industries = await showDialog(
context: context,
builder: (context) {
return IndustrySearchDialog(
menuListData: _menuListData,
title: 'Select Industries',
options: _menuListData.industries.values
.toList(),
selectedOptions: selectedOptions,
onSelectedOptionListChanged: (options) {
selectedOptions = options;
print(selectedOptions);
});
});
},
child: Text(
'INDUSTRIES',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () async {
stages = await showDialog(
context: context,
builder: (context) {
return StageSearchDialog(
context: context,
menuListData: _menuListData,
title: 'Select Stages',
options:
_menuListData.stages.values.toList(),
selectedOptions: selectedOptions,
onSelectedOptionListChanged: (options) {
selectedOptions = options;
print(selectedOptions);
});
});
},
child: Text(
'STAGES',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () async {
languages = await showDialog(
context: context,
builder: (context) {
return LanguageSearchDialog(
menuListData: _menuListData,
title: 'Select Languages',
options: _menuListData.languages.values
.toList(),
selectedOptions: selectedOptions,
onSelectedOptionListChanged: (options) {
selectedOptions = options;
print(selectedOptions);
});
});
},
child: Text(
'LANGUAGES',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () async {
locations = await showDialog(
context: context,
builder: (context) {
return LocationSearchDialog(
menuListData: _menuListData,
title: 'Select Locations',
options: _menuListData.locations.values
.toList(),
selectedOptions: selectedOptions,
onSelectedOptionListChanged: (options) {
selectedOptions = options;
print(selectedOptions);
});
});
},
child: Text(
'LOCATIONS',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
SizedBox(
height: 40,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ButtonTheme(
textTheme: ButtonTextTheme.primary,
minWidth: 60,
child: RaisedButton(
onPressed: () {
Navigator.of(this.widget.context).pop();
},
color: Color(0xff2b57ff),
child: Text(
'Cancel',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
),
ButtonTheme(
textTheme: ButtonTextTheme.primary,
minWidth: 60,
child: RaisedButton(
onPressed: () {
_proposalSearchBloc.dispatch(ProposalFilterFetchEvent(advanceFilter:
FilterProposalPost(......)));
Navigator.pop(context);
print(("value from dialog" +
industries.toString()));
print(("value from dialog" +
stages.toString()));
print(("value from dialog" +
locations.toString()));
print(("value from dialog" +
languages.toString()));
},
color: Color(0xff2b57ff),
child: Text(
'Apply',
style: TextStyle(fontFamily: 'MyRaidPro'),
),
),
)
],
)
],
),
),
),
);
}
},
),
),
);
}
}
#BLOC
class ProposalSearchBloc
extends Bloc<ProposalSearchEvent, ProposalSearchState> {
final ProposalListingRepo proposalRepository;
List keywordSearchedProposalList = List();
List filteredProposalList = List();
ProposalSearchBloc({this.proposalRepository});
void proposalFilterPostParam(FilterProposalPost filterProposalPost) {
dispatch(ProposalSearchFetchEvent(filterProposalPost: filterProposalPost));
}
#override
ProposalSearchState get initialState => ProposalSearchFetchingState();
#override
Stream<ProposalSearchState> mapEventToState(event) async* {
try {
var filteredProposal;
print("proposal search even fired first time");
if (event is ProposalSearchFetchEvent) {
filteredProposal =
await proposalRepository.filterProposal(event.filterProposalPost);
} else if (event is ProposalFilterFetchEvent) {
print("filter event");
filteredProposal =
await proposalRepository.filterProposal(event.advanceFilter);
filteredProposalList.addAll(filteredProposal);
yield ProposalSearchFetchedState(filteredProposal: filteredProposal);
}
} catch (_) {
//print(error.toString());
yield ProposalSearchErrorState();
}
}
}
Finally I was able to solve the problem. I just forgot to use try catch blok in my bloc. This solves most of the problems of reloading the previous page after changing configuration from another page (DialogBox Box probably). I just had to make few changes in the Bloc code as:
#override
Stream<ProposalSearchState> mapEventToState(event) async* {
yield ProposalSearchFetchingState();
if (event is ProposalSearchFetchEvent) {
try {
print("proposal search");
filteredProposal =
await proposalRepository.filterProposal(event.filterProposalPost);
yield ProposalSearchFetchedState(
searchedProposal: filteredProposal);
} catch (error) {
print(error);
}
if (event is ProposalFilterFetchEvent) {
try {
print("proposal filtered");
filteredProposal =
await proposalRepository.filterProposal(event.filterProposalPost);
yield ProposalFilteredFetchedState(
filteredProposal: filteredProposal);
} catch (error) {
print(error.toString());
}
}
}
}