Flutter: Unhandled Exception: Unable to load asset - flutter

I am trying to build an app where one of the buttons should open a pdf. I used the guide in this link : https://pspdfkit.com/blog/2019/opening-a-pdf-in-flutter/ however it won't work on the first time the app is running it works only after a hot reload/restart. I have tried flutter clean. Also the output of the pubspec.yaml is exit code 0
flutter:
assets:
- PDFs/MyDoc.pdf
- assets/
Here is a snippet of the code:
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'package:path_provider/path_provider.dart';
const String _documentPath = 'PDFs/MyDoc.pdf';
void main() => runApp(MaterialApp(
home: FadyCard(),
));
class FadyCard extends StatefulWidget {
#override
_FadyCardState createState() => _FadyCardState();
}
class _FadyCardState extends State<FadyCard> {
Future<String> prepareTestPdf() async {
final ByteData bytes =
await DefaultAssetBundle.of(context).load(_documentPath);
final Uint8List list = bytes.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final tempDocumentPath = '${tempDir.path}/$_documentPath';
final file = await File(tempDocumentPath).create(recursive: true);
file.writeAsBytesSync(list);
return tempDocumentPath;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
title: Text('Document'),
centerTitle: true,
backgroundColor: Colors.grey[850],
elevation: 0,
),
bottomNavigationBar: BottomAppBar(
shape: const CircularNotchedRectangle(),
child: Container(
height: 50.0,
),
color: Colors.grey[850],
),
floatingActionButton: FloatingActionButton(
onPressed: () => {
prepareTestPdf().then((path) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullPdfViewerScreen(path)),
);
})
},
child: Icon(Icons.folder, color: Colors.amber,),
backgroundColor: Colors.grey[700],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
}
class FullPdfViewerScreen extends StatelessWidget {
final String pdfPath;
FullPdfViewerScreen(this.pdfPath);
#override
Widget build(BuildContext context) {
return PDFViewerScaffold(
appBar: AppBar(
title: Text("My Document"),
backgroundColor: Colors.grey[800],
),
path: pdfPath);
}
}
Thanks in advance.

FadyCard is the StateFull Widget you need update the PDF inside the setState.
Try like this (not tested)
onPressed: () => {
setState(() {
prepareTestPdf().then((path) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullPdfViewerScreen(path)),
);
})
})
}

Related

Flutter build not behaving as expected

I'm trying to make a note app but there is a yellow square showing on the screen.
I've included the main.dart code and also allnotesscreens.dart. I think there is something wrong with allnotesscreens code, but I don't know what.
Maybe _loadViewMode() part.
Why this problem is happening?!!!
Main.dart:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'providers/label_provider.dart';
import 'providers/note_provider.dart';
import 'package:provider/provider.dart';
import 'constants/app_constants.dart';
import 'screens/all_labels_screen.dart';
import 'screens/all_notes_screen.dart';
import 'screens/drawer_screen.dart';
main() {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
systemNavigationBarColor: ColorsConstant.grayColor,
),
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => NoteProvider()),
ChangeNotifierProvider(create: (_) => LabelProvider()),
],
builder: (context, child) => MaterialApp(
title: 'Note-App',
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.dark,
theme: customThemeData(context),
initialRoute: '/',
routes: {
'/': (context) => const AllNotesScreen(),
DrawerScreen.routeName: (context) => const DrawerScreen(),
AllLabelsScreen.routeName: (context) => const AllLabelsScreen(),
},
),
);
}
}
allnotesscreens.dart:
class AllNotesScreen extends StatefulWidget {
const AllNotesScreen({Key? key}) : super(key: key);
#override
State<AllNotesScreen> createState() => _AllNotesScreenState();
}
class _AllNotesScreenState extends State<AllNotesScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Container(
height: 200,
width: 100,
color: Colors.yellow,
),
),
);
}
String _viewMode = ViewMode.staggeredGrid.name;
bool _isLoading = false;
final _scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
setState(() {
_isLoading = true;
});
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
Future _loadViewMode() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('view-mode')) return;
setState(() {
_viewMode = prefs.getString('view-mode') ?? ViewMode.staggeredGrid.name;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text(
"all notes",
style: TextStyleConstants.titleAppBarStyle,
),
actions: [
if (context
.watch<NoteProvider>()
.items
.isNotEmpty)
IconButton(
onPressed: () {
showSearch(
context: context,
delegate: NoteSearch(isNoteByLabel: false),
);
},
icon: const Icon(Icons.search),
),
IconButton(
onPressed: () async {
final result = await changeViewMode(_viewMode);
setState(() {
_viewMode = result;
});
},
icon: _viewMode == ViewMode.staggeredGrid.name
? const Icon(Icons.view_stream)
: const Icon(Icons.grid_view),
),
const SizedBox(
width: 6,
)
],
),
drawer: const DrawerScreen(),
body: _isLoading
? const Center(
child: CircularProgressIndicator(),
)
: RefreshIndicator(
onRefresh: () => refreshOrGetData(context),
child: Consumer<NoteProvider>(
builder: (context, noteProvider, child) =>
noteProvider.items.isNotEmpty
? NoteListViewWidget(
notes: noteProvider.items,
viewMode: _viewMode,
scaffoldContext: _scaffoldKey.currentContext!,
)
: child!,
child: const NoNoteUIWidget(
title: "your notes after adding will appear here",
),
),
),
floatingActionButton: FloatingActionButton(
child: linearGradientIconAdd,
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const EditNoteScreen(),
));
},
),
);
}
}
}
The first few lines of your _AllNotesScreenState class are why there's a yellow square; that's what you're telling it to build.
class _AllNotesScreenState extends State<AllNotesScreen> {
// this build function here is what is drawing to the screen
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Container(
height: 200,
width: 100,
color: Colors.yellow,
),
),
);
}
Maybe it's just how you've pasted it in, but it appears as though you have a build function defined within the didChangeDependencies function. If you took it out of there, it would then make it apparent that you have two build functions defined for the class.
I'm assuming it's the second one that you actually want building.
#override
void didChangeDependencies() {
super.didChangeDependencies();
Future _loadViewMode() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('view-mode')) return;
setState(() {
_viewMode = prefs.getString('view-mode') ?? ViewMode.staggeredGrid.name;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
...

how save theme or color of my flutter app

please any one help me when I close my app the theme reback to defult theme,how can I save the theme when I pick color from colorpicker library and I use hive library to save data,
if there are any another libraries to save data better than hive please tell me
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/src/block_picker.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
await Hive.initFlutter();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter',
debugShowCheckedModeBanner: false,
//theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Box? box;
Color? z;
#override
void initState() {
super.initState();
openBox();
try {
getData();
} catch (e) {
print(e);
}
}
Future openBox() async {
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
box = await Hive.openBox('colorBox');
return;
}
void saveData(val) {
box!.put('color1', val);
}
void getData() {
setState(() {
z = Color(box!.get('color1'));
});
}
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
Color color = Colors.blue;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Counter"),
backgroundColor: z,
),
endDrawer: Drawer(
child: ListView(
children: [
ListTile(
title: Text("pick color"),
leading: Icon(Icons.color_lens),
onTap: () => showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text("select your color"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
BlockPicker(
onColorChanged: (Color value) {
saveData(value.value);
},
pickerColor: Colors.blue,
),
TextButton(
onPressed: () {
getData();
Navigator.pop(ctx);
},
child: Text("close"))
],
),
)),
),
],
),
),
body: Center(
child: Container(
width: double.infinity,
height: double.infinity,
child: TextButton(
onPressed: () {
incrementCounter();
},
child: Text(
'${counter}',),
),
),
),
);
}
}
I make code smaller as I can,and I remove all the style.
Hive should work for you,
alternatively you can use
Use the Shared Preference package and there you can store simple values as key pair values.Load that data in the init of the initial screen so that you can display the color as you need.
Step 1: Install flutter hive from https://pub.dev/packages/hive_flutter
Step 2: import 'package:hive_flutter/adapters.dart'; in your models
This class as of writing this answer contains two classes:
Color and TimeOfDay
Use hive. This is a benchmark blog that shows hive's performance capabilities: hive performance

FLUTTER/DART - TEXT not displaying to home.dart file within a FloatingActionButton

Having a problem with getting text to display in my home.dart file when it's entered in the FloatingActionButton.
Below is the code sample. Any suggestions where I am getting it wrong. I believe that the 'String value;' line must be within the same MaterialButton function, though not sure how to do it without ruining it further.
}`
I'm using a simple app here to demonstrade the behavior. You can test by copy and running this:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SomeScreen(),
);
}
}
class SomeScreen extends StatefulWidget {
#override
_SomeScreenState createState() => _SomeScreenState();
}
class _SomeScreenState extends State<SomeScreen> {
String value = '';
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () async {
await _createDialog(context);
setState(() {});
},
child: Icon(Icons.add),
backgroundColor: Colors.red,
),
body: Container(
color: Colors.blue,
child: Center(
child: Text(value),
),
),
);
}
_createDialog(context) async {
await showDialog(
context: context,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: Text('title'),
content: TextField(
onChanged: (text) {
value = text;
},
),
actions: <Widget>[
FlatButton(
child: Text('buttonText'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
}
}

Showing Material Dialog, No MaterialLocalizations found

I tried to make Dialog function on my app.
But the "No MaterialLocalizations found." error came out and it didn't open the popup window.
I don't know how to solve this issue even though I tried to find other references.
Please let me know how to fix this issue.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(OverApp());
}
class OverApp extends StatefulWidget {
#override
_OverAppState createState() => _OverAppState();
}
class _OverAppState extends State<OverApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('List'),
),
body: RaisedButton(
child: Text('Show Material Dialog'),
onPressed: _showMaterialDialog,
),
),
);
}
_showMaterialDialog() {
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text("Material Dialog"),
content: new Text("Hey!"),
actions: <Widget>[
FlatButton(
child: Text('Close me!'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
));
}
}
You need to put the MaterialApp in runApp (or make another widget and put the Scaffold in its build and use this new widget as the home of the MaterialApp).
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: OverApp()));
}
class OverApp extends StatefulWidget {
#override
_OverAppState createState() => _OverAppState();
}
class _OverAppState extends State<OverApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List'),
),
body: RaisedButton(
child: Text('Show Material Dialog'),
onPressed: _showMaterialDialog,
),
);
}
_showMaterialDialog() {
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text("Material Dialog"),
content: new Text("Hey!"),
actions: <Widget>[
FlatButton(
child: Text('Close me!'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
));
}
}

The method 'selectTime' isn't defined for the class '_createWeckerPage'

I used a casual showTimePicker in our first dart file (main.dart)
import 'package:flutter/material.dart';
import 'dart:async';
//import 'package:android_alarm_manager/android_alarm_manager.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CreateWeckerPage('Wecker erstellen'),
);
}
}
class CreateWeckerPage extends StatefulWidget{
CreateWeckerPage(this.name):super();
final String name;
#override
_CreateWeckerPage createState() => _CreateWeckerPage();
}
class _CreateWeckerPage extends State<CreateWeckerPage>{
TimeOfDay _time = new TimeOfDay.now();
//Zeit Picker Funktion
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _time,
builder: (BuildContext context, Widget child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child,
);
}
);
if(picked != null && picked != _time){
print('Timeselected: ${_time.toString()}');
setState((){
_time = picked;
});
}
}
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text('${widget.name}')
),
body: Container(
child: Column(
children: <Widget>[
Text('Time Selected: ${_time.toString()}'),
RaisedButton(
onPressed: (){
_selectTime(context);
},
child: Text(
"Zeit eingeben",
),
),
],
),
),
);
}
}
I wanted to refector the code and started to outsource the page in another dart file and the function _selectTime into another dart file for the functions. So i created a file which is called createWeckerPage.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:wecker/Funktions/timePicker.dart';
class CreateWeckerPage extends StatefulWidget{
CreateWeckerPage(this.name):super();
final String name;
#override
_CreateWeckerPage createState() => _CreateWeckerPage();
}
class _CreateWeckerPage extends State<CreateWeckerPage>{
TimeOfDay _time;
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text('${widget.name}')
),
body: Container(
child: Column(
children: <Widget>[
Text('Time Selected: ${_time.toString()}'),
RaisedButton(
onPressed: (){
testClass.testFunktion();
_time = _selectTime(context):
);
},
child: Text(
"Zeit eingeben",
),
),
],
),
),
);
}
}
and a timePicker.dart
import 'package:flutter/material.dart';
import 'dart:async';
Future<Null> _selectTime(BuildContext context) async {
TimeOfDay _time = TimeOfDay.now();
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _time,
builder: (BuildContext context, Widget child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child,
);
}
);
if(picked != null && picked != _time){
print('Timeselected: ${_time.toString()}');
return picked;
}
return _time;
}
The problem is, as written in the title that the method _selectTime is not defined in the createWeckerPage Class. How can I implement my Future _selectTime function to work inside my createWeckerPage.dart to display in the app?
Thank you in advance.
underline means private, you can remove _ underline
please change from
_selectTime(BuildContext context)
to
selectTime(BuildContext context)