I've followed the steps to fetch local JSON, I think the problem is because in the pubspec, when I change the name local JSON different name the console nothing error, so what issues do I have? it's my wrong or flutter update something? it's my code :
import 'dart:convert';
import 'package:fetch_local_data/model.dart';
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
List<Books> parseJson(String? json) {
if (json == null) {
return [];
}
List result = jsonDecode(json);
return result.map((e) => Books.fromJson(e)).toList();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<String>(
future: DefaultAssetBundle.of(context).loadString('assets/books.json'),
builder: (context, snapshot) {
List<Books> books = parseJson(snapshot.data);
print(books.length);
return ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
return Text(books[index].title);
});
},
),
);
}
}
pubspec
name: fetch_local_data
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.17.6 <3.0.0"
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
assets:
- assets/books.json
folder structure
Related
I am trying to create a SignIn page with Firebase authentication, but this error is happening in main.dart when I run the code:
This is the code: from main.dart:
import 'package:app_mypocket/services/auth_service.dart';
import 'package:app_mypocket/telas/home/homepage.dart';
import 'package:app_mypocket/telas/login/telalogin.dart';
[import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Pocket',
debugShowCheckedModeBanner: false,
theme: ThemeData(
),
home: HomePage(),
//routes: routes,
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) => Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData){
return HomePage();
} else{
return TelaLogin();
}
})
);
}
My pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
intl:
provider: ^6.0.4
shared_preferences: ^2.0.6
hive: ^2.0.4
hive_flutter: ^1.1.0
path_provider: ^2.0.2
sqflite: ^2.0.0+3
fl_chart: ^0.55.2
firebase_core: ^2.1.1
firebase_auth: ^4.1.0
cloud_firestore: ^4.0.3
Also, I have created a user manually in my project on the firebase website, so I am trying to logIn.
When logging into Firebase you normally provide options, like:
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize Firebase
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
These firebase_options are generated by running "flutterfire configure" (previously firebase configure iirc).
I think you forget this specific step. See the guide: https://firebase.google.com/docs/flutter/setup?platform=ios
The configuration file contains information about the apiKey, appId, projectId, bundle/app name and much more. Not providing it, will lead to a default/blank/unusable app.
Please I need assistance.
I have written below code to saved file selected from filepicker_windows to C: drive.
filepicker_windows worked well and it get my C: drive successfully But not saving the file.
It gives me ERROR "Exception has occurred.
NoSuchMethodError (NoSuchMethodError: Class 'String' has no instance getter 'bodyBytes'.
Receiver: "C:\Users\norak\OneDrive\Pictures\afdb\Capture.PNG"
Tried calling: bodyBytes)"
Below is my code, please help correct it.
pubspec.yaml File
name: file_manager
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
filepicker_windows: ^2.0.0
path_provider: ^2.0.1
provider: ^5.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
MAIN PAGE
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:filepicker_windows/filepicker_windows.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<String> getPicturesPath() async {
Directory docDir = await getApplicationDocumentsDirectory();
var pathList = docDir.path.split('\\');
pathList[pathList.length - 1] = 'Pictures';
var picturePath = pathList.join('\\');
print(picturePath);
return picturePath;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("File Management"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'Testing',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final file = OpenFilePicker()
..filterSpecification = {'All Files': '*.*'}
..defaultFilterIndex = 0
..defaultExtension = 'doc'
..title = 'Select a document';
final result = file.getFile();
if (result != null) {
print(result.path);
saveImage(result.path, 'ik.jpg');
print("Saved");
}
},
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void saveImage(imageData, String imageName) async {
var picturesPath = await getPicturesPath();
var thetaImage = await File(join(picturesPath, 'theta_images', imageName))
.create(recursive: true);
await thetaImage.writeAsBytes(imageData.bodyBytes);
}
}
await thetaImage.writeAsBytes(imageData.bodyBytes); //This is the line that is given error
Please advice
Why don't you debug your code? It's a string. That's why you got the error.
Change the code to:
await thetaImage.writeAsBytes(File(imageData).readAsBytesSync());
> final directory = await getApplicationDocumentsDirectory();
final path = directory.path;
final file = File(path);
I'm having problems with mobx and radiobox: screen don't update when selected. I think it's a silly mistake, here are my main.dart, teste_store.dart and pubspec.yaml. The partial file .g was generated with build_runner and mobx_codegen.
A message appears when I run it: "No observables detected in the build method of Observer". I thought testeStore.selected was an observable and when changes triggers Observer to rebuild.
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:teste_flutter/teste_store.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TesteStore testeStore = TesteStore();
#override
Widget build(BuildContext context) {
List<String> options = ["Option 1", "Option 2", "Option 3"];
return Scaffold(
appBar: AppBar(
title: Text("Test Flutter"),
),
body: Center(
child: Observer(
builder: (_){
return ListView.builder(
itemCount: options.length,
itemBuilder: (context, index) {
return RadioListTile<int>(
title: Text(options[index]),
value: index,
groupValue: testeStore.selected,
onChanged: testeStore.changeSelected,
);
},
);
}
)
),
);
}
}
teste_store.dart
import 'package:mobx/mobx.dart';
part 'teste_store.g.dart';
class TesteStore = _TesteStore with _$TesteStore;
abstract class _TesteStore with Store {
#observable
int selected = 0;
#action
void changeSelected(int newSelected) {
selected = newSelected;
}
}
pubspec.yaml
name: teste_flutter
description: A new Flutter application.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
mobx: ^1.2.1+2
flutter_mobx: ^1.1.0+2
provider: ^4.3.2+2
dev_dependencies:
flutter_test:
sdk: flutter
build_resolvers: ^1.3.10
mobx_codegen: ^1.1.0+1
build_runner: ^1.10.2
flutter:
uses-material-design: true
Edit 1 and 2:
I put the solution I found here and I shouldn't. Writing down in an answer box.
Talking to #BambinoUA, we found out a solution, just to add insight why his solution works.
I did put List view inside a Column with a sibling text widget with testeStore.selected like a text, now everything updates.
child: Observer(
builder: (_){
return Column(
children: [
Text(testeStore.selected.toString()),
ListView.builder(
itemCount: options.length,
itemBuilder: (context, index) {
return RadioListTile<int>(
title: Text(options[index]),
value: index,
groupValue: testeStore.selected,
onChanged: testeStore.changeSelected,
);
},
),
],
);
}
)
Back to original code I tried to only use print(testeStore.selected); before return inside builder of the Observer and it worked:
child: Observer(
builder: (_){
print(testeStore.selected);
return ListView.builder(
When I put inside the itemBuilder from RadioListTile don't work.
child: Observer(
builder: (_){
return ListView.builder(
itemCount: options.length,
itemBuilder: (context, index) {
print(testeStore.selected);
return RadioListTile<int>(
I assume Observer don't look changes inside other widgets builder.
I see that your TesteStore class is derived from private _TesteStore class. Maybe this is the case? And the error message looks reasonable. Try to make class with #observable public and re-build part file.
Update
Try to do intermediate assignments in Observer builder
final selected = testeStore.selected;
and then use new local variable selected inside inner builder.
Try to use ListView instead ListView.builder.
Try wrap with Observer not the List but RadioListTile.
I'm just experimenting with Flutter for the past couple of days. I am trying to add an image but it won't show up at all.
Am I missing something obvious?
main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PicHuntingNigga',
home: Scaffold(
appBar: AppBar(
title: Text('PicHunting-Nigga'),
centerTitle: true,
backgroundColor: Colors.red,
),
body: new Center(
child: new MyCameraWidget(),
),
),
);
}
}
class MyCameraWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
var assetImage = new AssetImage('assets/images/camera1.png');
var image = new Image(image: assetImage, width: 225.0, height: 225.0);
return new Container(child: image);
}
}
and my pubspec.yaml
name: flutter_app
description: A new Flutter application.
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/camera.png
- assets/images/camera1.png
- assets/images/
My folder structure
After I run the emulator - everything shows up minus the picture.I can replace the image with child: Text('asdasdasda'), and it will render the text but not the image.
Also see this example here https://flutter.dev/docs/development/ui/assets-and-images
Widget build(BuildContext context) {
// ...
return DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/background.png'),
// ...
),
// ...
),
);
// ...
}
So I solved it!
Not sure how....I just turned off my laptop and then turned it on. I also had dinner and now it's working.
So if you're stuck with a similar issue - have dinner? that seemed to have been the solution for me.
Error says:
NoSuchMethodError: The getter 'length' was called on null
It is a basic flutter music player App.
main.dart
import 'package:flute_music_player/flute_music_player.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Song> _songs;
#override
void initState() {
// TODO: implement initState
super.initState();
initPlayer();
}
void initPlayer() async{
var songs = await MusicFinder.allSongs();
songs=new List.from(songs);
setState(() {
_songs = songs;
});
}
#override
Widget build(BuildContext context) {
Widget home(){
new Scaffold(
appBar: new AppBar(title: new Text("Music App"),
),
body: new ListView.builder(
itemCount: _songs.length,
itemBuilder: (context,int index){
return new ListTile(
leading: new CircleAvatar(
child: new Text(_songs[index].title[0]),
),
title: new Text(_songs[index].title),
);
}),
);
}
return new MaterialApp(
home: home(),
);
}
}
pubspec.yaml
name: music_player
description: A new Flutter application.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
flute_music_player:
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
It should show the list of musics as result but gives an unexpected error.I am running on android.Plz help me out.
It should show the list of musics as result but gives an unexpected error.I am running on android.Plz help me out.
Change itemCount: _songs.length to itemCount: _songs?.length ?? 0 - it helps to avoid exception
Since you're performing an async operation, that would take certain amount of time so when your app first builds, the songs array is null. Try to start with an empty array instead of a null array: List<Song> _songs = []; then, when the async operation is completed the setState will make the widget to rebuild and show the array with data.