faithoflifedev / yt

Multiple YouTube APIs in one Dart library
MIT License
10 stars 3 forks source link

I wrote the code following the sample code, but an error occurred. #8

Closed photofarm closed 9 months ago

photofarm commented 9 months ago

here is my source code

import "dart:io";

import "package:flutter/material.dart"; import "package:image_picker/image_picker.dart"; import "package:yt/yt.dart";

void main() { runApp(const MyApp()); }

class MyApp extends StatelessWidget { const MyApp({super.key});

// This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: "Flutter Demo", theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: "Flutter Demo Home Page"), ); } }

class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title});

final String title;

@override State<MyHomePage> createState() => _MyHomePageState(); }

class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: OutlinedButton( onPressed: () async { XFile? file = await ImagePicker().pickVideo(source: ImageSource.gallery); final yt = Yt.withKey("--- My API key ---"); final body = <String, dynamic>{ "snippet": { "title": "TEST title", "description": "Test Description", "tags": [ "tag1", "tag2" ], "categoryId": "22" }, "status": { "privacyStatus": "private", "embeddable": true, "license": "youtube" } }; final vfile = File(file!.path); final videoItem = await yt.videos.insert(body: body, videoFile: vfile); print(videoItem); }, child: const Text("Upload..."), ), ), ); } }

The above code was written as an exercise.

However, the following error occurs:

E/flutter ( 8711): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value E/flutter ( 8711): #0 Yt.videos (package:yt/src/yt_base.dart:43:31) E/flutter ( 8711): #1 _MyHomePageState.build.<anonymous closure> (package:yt_exam/main.dart:72:40) E/flutter ( 8711): <asynchronous suspension> E/flutter ( 8711):

faithoflifedev commented 9 months ago

Hi @photofarm,

The problem is with this:

final yt = Yt.withKey("--- My API key ---");

When authenticating with an API key Youtube restricts the API features that are available. You instead need to use:

final yt = Yt.withOAuth();

//or

final yt = Yt.withGenerator(refreshTokenGenerator);

Where withOauth is covered in the README here and withGenerator is covered here.

Not knowing the goal of your app I can't really say which is better to use, but if users of your app are uploading to their own YouTube accounts then withGenerator is the better option.

I'll probably have to provide a better error message for this scenario for the future.